$.fn.clearForm = function() {
  return this.each(function() {
    var type = this.type, tag = this.tagName.toLowerCase();
    if (tag == 'form')
      return $(':input',this).clearForm();
    if (type == 'text' || type == 'password' || tag == 'textarea')
      this.value = '';
    else if (type == 'checkbox')
      this.checked = false;
    else if (tag == 'select')
      this.selectedIndex = 0;
  });
};

function showCompany(){
	$("#error").hide();
	$("#where_to_buy :input").removeClass("error");
	$(".user .outfit").fadeIn("fast");
	$(".user .outfit select").addClass("required");
	$(".contact div.individual").fadeOut(function(){
		$(this).remove().appendTo(".hidden");
		$(".hidden div.company").hide().remove().appendTo(".contact").fadeIn();
	});
}
function showIndividual() {
	$("#error").hide();
	$("label.error").hide();
	$("#where_to_buy :input").removeClass("error");
	$(".user .outfit").fadeOut("fast");
	$(".user .outfit select").removeClass("required");
	$(".contact div.company").fadeOut(function(){
		$(this).remove().appendTo(".hidden");
		$(".hidden div.individual").hide().remove().appendTo(".contact").fadeIn();
	});
}

$(document).ready(function() {
	$("#loading").ajaxStart(function(){
	   $(this).show();
	 });
	$("#loading").ajaxComplete(function(){
	   $(this).fadeOut();
	 });
	
jQuery.validator.messages.required = "";
jQuery.validator.addMethod("phoneUS", function(phone_number, element) {
    phone_number = phone_number.replace(/\s+/g, ""); 
	return this.optional(element) || phone_number.length > 9 &&
		phone_number.match(/^(1-?)?(\([2-9]\d{2}\)|[2-9]\d{2})-?[2-9]\d{2}-?\d{4}$/);
}, "Please specify a valid phone number");

	$("#where_to_buy, #register").validate({
		highlight: function(element, errorClass) {
			$(element).addClass(errorClass);
		},
		unhighlight: function(element, errorClass) {
			$(element).removeClass(errorClass);
		},
		invalidHandler: function(e, validator) {			
			var errors = validator.numberOfInvalids();
			if (errors) {
				var message = errors == 1
					? 'You missed 1 field.'
					: 'You missed ' + errors + ' fields.';
				$("div#error span").html(message);
				$("div#error").show();
			} else {
				$("div#error").hide();
			}
		},
		rules: {
			phone: {
			      required: true,
			      phoneUS: true
			    }
		},
		messages: {
		    "hazards[]": {
		       required: "Please select at least one hazard."
		     },
			"outfit": {
				required: "Please select the amount of people you are looking to outfit."
			},
			"country_select": {
				required: "Please select your country."
			},
			"state_select": {
				required: "Please select your state."
			},
			"province_select": {
				required: "Please select your province."
			}
		   },
		errorPlacement: function(error, element) {
			if (element.attr("name") == "hazards[]") {
				error.prependTo(".hazards");
			} else if (element.attr("name") == "outfit") {
				error.prependTo(".user");
			} else if (element.attr("name") == "country_select" || element.attr("name") == "state_select" || element.attr("name") == "province_select") {
				error.prependTo(".location-select");
			} else if (element.attr("name") == "preferred") {
				$("input[name='preferred']").next(".preferred").addClass("error");
			}
		}
	});
	
	$("#clear").click(function(){
		$('form#where_to_buy').clearForm();
		return false;
	});
	
	$("#location").change(function(){
		var loc = $("#location").val();
		var location = loc.split(' ').join('-').toLowerCase();
		$(".secondary:visible").removeClass("required").removeClass("error").hide();
		$(".secondary").attr('selectedIndex',0);
		$(".location-select label.error").hide();
		
		if(loc == "United States") {
			$("#state-select").addClass("required").show();
		} else if(loc == "Canada") {
			$("#province-select").addClass("required").show();
		} else {
			$("#country-select").addClass("required").show();
		}
	});
	
	$("#state-select").change(function(){
		var selected = $("#state-select option:selected").val();
		
		$("#secondary .sales-rep").load("/find-out-more/sales-rep/", {'state':selected});
		$("#rep-id").load("/find-out-more/sales-rep/id/", {'state':selected});
	});
	
	$("#province-select").change(function(){
		var selected = $("#province-select option:selected").val();

		$("#secondary .sales-rep").load("/find-out-more/sales-rep/", {'province':selected});
		$("#rep-id").load("/find-out-more/sales-rep/id/", {'province':selected});
	});
	
	$("#country-select").change(function(){
		var selected = $("#country-select option:selected").val();
		$("#secondary .sales-rep").load("/find-out-more/sales-rep/", {'country':selected});
		$("#rep-id").load("/find-out-more/sales-rep/id/", {'country':selected});
	});
	
	//$(".outfit").hide();
	$(".user a").click(function(){
		var type = $("img", this).attr("alt");
		$(".user input[value='" + type + "']").attr("checked","checked");
		if(type == "Company") {
			showCompany();
		} else {
			showIndividual();
		}
		return false;
	});
	$(".user input").click(function(){
		if($(this).val() == "Company") {
			showCompany();
		} else {
			showIndividual();
		}
	});
	
	$(".hazards ul li img,.hazards ul li span").toggle(function(){
		$(this).parent().children(":input").attr('checked', true);
	}, function() {
		$(this).parent().children(":input").removeAttr('checked');
	});
	
	$('.with-other').each(function() {
	  var $other = $('#' + this.id + '-other').parent();
	  $(this).change(function() {
  	  if ($(this).val() == 'Other') {
  	    $other.show();
  	  }
  	  else {
  	    $other.hide();
  	  }
  	});
  	$other.hide();
	});
});