var CurrentCountry = "";
var PhoneError = "Please enter valid phone number.";

$(document).ready(function() {
	$('#na_phone_area').autotab({ target: $('#na_phone_exchange'), format: 'numeric' });
	$('#na_phone_exchange').autotab({ target: $('#na_phone_station'), format: 'numeric', previous: $('#na_phone_area') });
	$('#na_phone_station').autotab({ previous: $('#na_phone_exchange'), format: 'numeric' });
	$('#phone_ext').numeric();
	$('#o_phone').numeric({allow:"-.+ "});
	$('#city').alpha({allow:" "});
	$('#first_name').alpha({allow:" -'"});
	$('#last_name').alpha({allow:" -'"});
	$('#other_postal').alphanumeric({allow:" "});
	$('#postal').alphanumeric();
	$('#zip').numeric();
	
	$('#first_name').change(function() {ValidateFirstName($(this));});
	$('#last_name').change(function() {ValidateLastName($(this));});
   $('#email').change(function() {ValidateEmail($(this));});
   $('#address').change(function() {ValidateAddress($(this));});
   $('#postal').change(function() {ValidatePostal($(this));});
   $('#zip').change(function() {ValidateZip($(this));});
	$('#city').change(function() {ValidateCity($(this));});
	$('#company').change(function() {ValidateCompany($(this));});
	$('#prov').change(function() { ValidateDropDown($(this),"state", "Please select a province."); });
	$('#state').change(function() { ValidateDropDown($(this),"state", "Please select a state."); });
	$('#industry').change(function() { ValidateDropDown($(this),"industry", "Please select an industry."); });
	
	// Use hidden form to actually post, so that no javascript = no posting to salesforce
	
	// If the user refreshes, the form could have values populated by the browser
	var Form = document.forminfo;
	
	if (Form.first_name.value.length > 0)
      ValidateFirstName($('#first_name'));
      
   if (Form.last_name.value.length > 0)
      ValidateLastName($('#last_name'));
	
	if (Form.email.value.length > 0)
      ValidateEmail($('#email'));
      
   if (Form.company.value.length > 0)
      ValidateCompany($('#company'));
  
   if (Form.address.value.length > 0)
      ValidateAddress($('#address'));
      
   if (Form.city.value.length > 0)
      ValidateCity($('#city'));
   
   ChangeCountry(Form);
   
   if (CurrentCountry == "Canada")
   {
      if (Form.postal.value.length > 0)
         ValidatePostal($('#postal'));
   }
   else if (CurrentCountry == "USA")
   {
      if (Form.zip.value.length > 0)
         ValidateZip($('#zip'));
   }
});

function ValidateDropDown(field, fieldName, msg)
{
   if (field.val() == "Select")
   {
      ErrorMsg(fieldName, msg);
      return false;
   }
   
   ClearMsg(fieldName);
   
   return true;
}

function ValidatePhoneArea(form, source)
{
   var area = form.na_phone_area.value;
   var exchange = form.na_phone_exchange.value;
   var station = form.na_phone_station.value;
   
   if (source)
   {   
      if (exchange.length > 0 && !ValidatePhoneExchange(form, false))
         return;
      
      if (station.length > 0 && !ValidatePhoneStation(form, false))
         return;
   }
   
   if (area.length < 3 || parseInt(area,10) <= 199 || parseInt(area,10) >= 990)
   {
      ErrorMsg("phone", PhoneError);
      return false;
   }
   
   if (source)
   {
      if (station.length > 0 && exchange.length > 0)
         ClearMsg("phone");
   }
   
   return true;
}

function ValidatePhoneExchange(form, source)
{
   var area = form.na_phone_area.value;
   var exchange = form.na_phone_exchange.value;
   var station = form.na_phone_station.value;
   
   if (source)
   {
      if (!ValidatePhoneArea(form, false))
         return;

      if (station.length > 0 && !ValidatePhoneStation(form, false))
         return;
   }
   
   if (exchange.length < 3 || parseInt(exchange,10) <= 199 || parseInt(exchange,10) == 555)
   {
      ErrorMsg("phone", PhoneError);
      return false;
   }
   
   if (source)
   {
      if (area.length > 0 && station.length > 0)
         ClearMsg("phone");
   }
   return true;
}

function ValidatePhoneStation(form, source)
{
   var station = form.na_phone_station.value; 
   
   if (source)
   {
      if (!ValidatePhoneArea(form, false))
         return;
         
      if (!ValidatePhoneExchange(form, false))
         return;
   }
   if (station.length < 4)
   {
      ErrorMsg("phone", PhoneError);
      return false;
   }
   if (source)
      ClearMsg("phone");
   
   return true;
}

function ValidateCompany(field)
{
   if (field.val().length == 0)
   {
      ErrorMsg("company","Please enter a company name.");
      return false;
   }
   
   ClearMsg("company");
   
   return true;
}

function ValidateCity(field)
{
   if (field.val().length == 0)
   {
      ErrorMsg("city","Please enter a city.");
      return false;
   }
   
   ClearMsg("city");
   
   return true;
}

function ValidatePhone(field)
{
   var pattern = new RegExp('[^0-9]+', 'g');
	var num = field.value.replace(pattern, '');
	var PhoneNumber = field.value;
	var Ext = $('#phone_ext').val();
	if (Ext > 0)
	   PhoneNumber += ", " + Ext;
	
	if (PhoneNumber.length > 40)
	{
	   ErrorMsg("phone",PhoneError);
	   return false;
	}
	
	if (num.length == 0)
	{
	   ErrorMsg("phone",PhoneError);
	   return false;
	}
	
   for (var i = 1; i < num.length; i++)
   {
      if (num.charAt( i ) != num.charAt(i-1))
      {
         ClearMsg("phone");
         return true;
      }
   }
   
   ErrorMsg("phone",PhoneError);
   
   return false;
}

function ValidateEmail(field) 
{
   var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
   var address = field.val();
   if(reg.test(address) == false) 
   {
      ErrorMsg('email', 'Correct email format: you@abc.com');
      return false;
   }
   
   ClearMsg('email');
   
   return true;
}

function ErrorMsg(field, msg)
{
   var element = "#" + field + "_error";
   $(element).text("Error: " + msg);
   $(element).removeClass();
   $(element).addClass("error");
}

function ClearMsg(field)
{
   var element = "#" + field + "_error";
   $(element).removeClass();
   $(element).html("&nbsp;");
}

function SetMsg(field, msg)
{
   var element = "#" + field + "_error";
   $(element).removeClass();
   $(element).text(msg);
}

function ValidateFirstName(field)
{
   return ValidateName(field,"Please enter your first name."); 
}

function ValidateLastName(field)
{
   return ValidateName(field,"Please enter your last name."); 
}

function ValidateName(field, msg)
{
   var name = field.val();
   var fieldName = field.attr("name");
   if (name.length == 0)
   {
      ErrorMsg(fieldName, msg);
      return false;
   }
   
   ClearMsg(fieldName);
   
   return true;
}

function ValidateZip(field)
{
   if (field.val().length < 5)
   {
      ErrorMsg("zip","Invalid Zip Code");
      return false;
   }
   
   ClearMsg("zip");   
   return true;
}

function ValidateAddress(field)
{
   var address = field.val();
   if (address.length <= 5 || address.length > 255)
   {
      ErrorMsg("address","Please enter a mailing address.");
      return false;
   }
   
   ClearMsg("address");
   return true;
}

function ValidatePostal(field)
{
   field.val(field.val().toUpperCase());
   var postal = field.val();
   var validation = /^([ABCEGHJKLMNPRSTVXY]\d[ABCEGHJKLMNPRSTVWXYZ])\ {0,1}(\d[ABCEGHJKLMNPRSTVWXYZ]\d)$/
   if (!postal.match(validation))
   {
      ErrorMsg("zip","Invalid Postal Code");
      return false;
   }
   
   ClearMsg("zip");
   return true;
}

function ChangeCountry(form)
{
   if (form.country.value == "-")
   {
      form.country.selectedIndex = 0;
      return;
   }
	switch (form.country.value)
   {
      case "Canada":
      {
         CurrentCountry = "Canada";
         // Show Canada fields
         $("#zip_label").text("* Postal Code:");
         $("#other_phone").hide();
         $("#na_phone").show();
         $("#other_state").hide();
         $("#us_state").hide();
         $("#ca_state").show();
         $("#other_postal").hide();
         $("#zip").hide();
         $("#postal").show();
         $("#state_label").text("* Province:");
      } break;
      case "USA":
      {
         CurrentCountry = "USA";
         // Show US Fields
         $("#zip_label").text("* Zip Code:");
         $("#other_phone").hide();
         $("#na_phone").show();
         $("#ca_state").hide();
         $("#other_state").hide();
         $("#us_state").show();
         $("#postal").hide();
         $("#other_postal").hide();
         $("#zip").show();
         $("#state_label").text("* State:");
      } break;
      default:
      {
         CurrentCountry = "Other";
         // Show other fields
         $("#zip_label").text("Postal Code:");
         $("#na_phone").hide();
         $("#other_phone").show();
         $("#ca_state").hide();
         $("#us_state").hide();
         $("#other_state").show();
         $("#postal").hide();
         $("#zip").hide();
         $("#other_postal").show();
         $("#state_label").text("State/Region:");
         $("#zip_error").text(" ");
         $("#state_error").text(" ");
      } break;
   }
}

function ValidateForm()
{
   var ValidForm = true;
   
   if (!ValidateFirstName($('#first_name')))
      ValidForm = false;
   
   if (!ValidateLastName($('#last_name')))
      ValidForm = false;
   
   if (!ValidateCompany($('#company')))
      ValidForm = false;
      
   if (!ValidateDropDown($('#industry'), "industry", "Please select an industry."))
         ValidForm = false;
      
   if (!ValidateEmail($('#email')))
      ValidForm = false;
   
   if (CurrentCountry == "Other")
   {
      if (!ValidatePhone(document.forminfo.o_phone, true))
         ValidForm = false;
   }
   else
   {
      if (!ValidatePhoneStation(document.forminfo, true))
         ValidForm = false;
   }
      
   if (!ValidateAddress($('#address')))
      ValidForm = false;
   
   if (!ValidateCity($('#city')))
      ValidForm = false;
   
   if (CurrentCountry == "Canada")
   {
      if (!ValidatePostal($('#postal')))
         ValidForm = false;
      if (!ValidateDropDown($('#prov'), "state", "Please select a province."))
         ValidForm = false;
   }
   else if (CurrentCountry == "USA")
   {
      if (!ValidateZip($('#zip')))
         ValidForm = false;
      if (!ValidateDropDown($('#state'), "state", "Please select a state."))
         ValidForm = false;
   }
      
   if (ValidForm)
      PostForm();
   else
      alert("Please make sure you've filled in the form correctly. Fields with missing or incorrect information will have an error message beside them.");
      
   return false;
}

function GetNAPhone()
{
   var PhoneNumber = $('#na_phone_area').val() + "-" + $('#na_phone_exchange').val() + "-" + $('#na_phone_station').val();
   var Ext = $('#phone_ext').val();
   
   if (Ext.length > 0)
      PhoneNumber += ", " + Ext;
      
   return PhoneNumber;
}

function GetOPhone()
{
   var PhoneNumber = $('#o_phone').val()
   var Ext = $('#phone_ext').val();
   
   if (Ext.length > 0)
      PhoneNumber += ", " + Ext;
      
   return PhoneNumber;
}

function PostForm()
{
   $('#a_first_name').val($('#first_name').val());
   $('#a_last_name').val($('#last_name').val());
   $('#a_title').val($('#title').val());
   $('#a_industry').val($('#industry').val());
   $('#a_company').val($('#company').val());
   $('#a_email').val($('#email').val());
   
   $('#a_address').val($('#address').val());
   $('#a_city').val($('#city').val());
   
   if (CurrentCountry == "USA")
   {
      $('#a_phone').val(GetNAPhone());
      $('#a_state').val($('#state').val());
      $('#a_zip').val($('#zip').val());
   }
   else if (CurrentCountry == "Canada")
   {
      $('#a_phone').val(GetNAPhone());
      $('#a_state').val($('#prov').val());
      $('#a_zip').val($('#postal').val());
   }
   else
   {
      $('#a_phone').val(GetOPhone());
      $('#a_state').val($('#o_state').val());
      $('#a_zip').val($('#other_postal').val());
   }
   
   
   $('#a_country').val($('#country').val());
   $('#a_hear').val($('#hear').val());
   $('#a_db').val($('#db').val());
   $('#a_vendors').val($('#vendors').val());
   $('#a_timeframe').val($('#timeframe').val());
   $('#a_employees').val($('#employees').val());
   
   $('#posting_form').submit();
}