$.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' || type == 'radio')
	    this.checked = false;
	  else if (tag == 'select')
	    this.selectedIndex = -1;
	});
};
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");

$('document').ready(function(){
	$('#iconmenu > #panel1c > span > a').click(function(event){
		var valid_form = $(".dvFrmField").validate({
			rules: {
				firstName: {
					required: true,
					maxlength: 255
				},
				lastName: {
					required: true,
					maxlength: 255
				},
				phone: {
					required: true,
					phoneUS: true
				},
				email: {
					required: true,
					maxlength: 255,
					email: true
				},
				messages: {
					phone: "A valid phone number is required.",
					email: "A valid email address is required."
				}
			}
		}).form();

		if(valid_form){
			if($('#agree_to_terms:checked').length == 1) {
				//var phone	= $('#phone').val();
				//$('#phone').val(phone.replace(/[^0-9]/g,""));

				var my_data = $('.dvFrmField').serialize();

				$('.dvFrmField input, .dvFrmField select').attr('disabled', 'disabled');
				$('.dvFrmField').prepend($('<div class="submitting"><img src="images/ajax_loader.gif" /><p>Your data is processing.</p></div>'));

				$.ajax({
					type: "POST",
					url: "submit_trial.php",
					data: my_data,
					success: function(msg){
						if(msg == "success") {
							window.location = "signup.php";
						}
						else {
							setTimeout(function(){
								$('.dvFrmField input, .dvFrmField select').removeAttr('disabled');
								$('.submitting').remove();
							}, 500);
						}
					}
				});
			} else {
				alert("You must agree to the Terms and Conditions");
			}
		}

		event.preventDefault();
	});

	$('#t_a_c').click(function(event){
		var tac = window.open("/terms.html", "Terms and Conditions", "width=600,height=500,scrollbars=yes");
		event.preventDefault();
	});
});
