$(document).ready(function(){
	
	$('#company-identification').tabs();
	
	$(".storycontrol").click(function(e) {
		e.preventDefault();
		var control = $(this).attr('id');
		control = control.split("-");
		control = control[0];
		closemsg = '<strong>- Close Story</strong>'
		openmsg = '<strong>+ Read More</strong>'
		if($("#"+control+"-more").hasClass('closed')){
			$(this).html(closemsg);
			$("#"+control+"-more").removeClass('closed')
			$("#"+control+"-more").addClass('opened')
		} else {
			$(this).html(openmsg);
			$("#"+control+"-more").removeClass('opened')
			$("#"+control+"-more").addClass('closed')
		}
		$("#"+control+"-more").toggle('fast');
	});

	$('.close').click(function(e) {
		e.preventDefault();
		var control = $(this).attr('id');
		control = control.split("-");
		control = control[0];
		openmsg = '<strong>+ Read More</strong>'

			$('#'+control+'-open').html(openmsg);
			$("#"+control+"-more").removeClass('opened')
			$("#"+control+"-more").addClass('closed')

		$("#"+control+"-more").toggle('fast');									
	});

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");

	/*****  Agent Contact *******/
$('#agent_submit').click(sendAgent)
	/*****  Requst Product Info  *******/
$('#product_submit').click(sendProduct)

//******* Add functionality to checkboxes :: Product Info
	$(".checklist .checkbox-select").click(
		function(event) {
			event.preventDefault();
			$(this).parent().addClass("selected");
			$(this).parent().find(":checkbox").attr("checked","checked");
		}
	);

	$(".checklist .checkbox-deselect").click(
		function(event) {
			event.preventDefault();
			$(this).parent().removeClass("selected");
			$(this).parent().find(":checkbox").removeAttr("checked");
		}
	);
//******* END -  Add functionality to checkboxes :: Product Info

	// tests for valid email
	function is_email(s){
		var reg = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
		return reg.test(s);
	}

	// tests for valid url
	function is_url(s){
		var reg = /(http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/;

		return reg.test(s);
	}
$('.example').example(function() {
  return $(this).attr('title');
});

 // Check value of contactMethod in case user navigated 
			// away from page after selecting a contact method
			// this will open the phone options if phone is selected
			// Check value of contactMethod upon selection
     $("#contactMethod").change(onSelectChange); 
 });  
 function onSelectChange(){  
     var selected = $("#contactMethod option:selected");       
     var output = "";  
		  if(selected.val() == 'Contact Method:'){ 
		 	// Remove phone options
         $(".phone").css('display','none');
				 $(".email").css('display','none');
		  	 $(".mail").css('display','none');
     }
     if(selected.val() == 'Phone'){  
		 	// Dispaly additional phone options
       $(".mail").css('display','none'); 		  
			 $(".email").css('display','none');
			 $(".phone").toggle("slow");
     }
		 if(selected.val() == 'Email'){
			 // Remove phone options
			 $(".phone").css('display','none');
			 $(".mail").css('display','none');
       $(".email").toggle("slow");
     }
		 if(selected.val() == 'Mail'){  
		 	// Remove phone options
			$(".phone").css('display','none');
			$(".email").css('display','none');
      $(".mail").toggle("slow");
     } 
		 // Close
 }



function checkForm() {
	
	method  = $('#contactMethod').val()

	switch(method)
	{
		case 'Email':

			email = $('#email_address');
			email = email.val();
			filter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
			if (filter.test(email)){
				if ($('#email_address').val() != $('#confirm_email_address').val()) {
					errormsg = "Please confirm that the email address you entered is the same in both fields.";
					setErrorMsg(errormsg);
					return false;
				} else {

					return true;
				}
			} else {
				errormsg = "Please enter a valid email address.";
				setErrorMsg(errormsg);
				return false;
			}
			break;
		case 'Phone':
			phoneNo = $('#contactMethod_phone');
			phoneNo = phoneNo.val();
			filter = /^[2-9]\d{2}-\d{3}-\d{4}/; 
			if (filter.test(phoneNo)){
				if ($('#contactMethod_phone_time').val() == "") {
					errormsg = "Please specify the time of day that you prefered to be contacted.";
					setErrorMsg(errormsg);
					return false;
				}
			} else {
				errormsg = "Please enter a valid phone number in the following format xxx-xxx-xxxx.";
				setErrorMsg(errormsg);
				return false;
			}
			break;
		case 'Mail':
			if ($('#address1').val() == "" || $('#city').val() == "" || $('#state').val() == "" || $('#zip').val() == "") {
				errormsg = "Please verify your address.";
				setErrorMsg(errormsg);
				return false;
			}
			break;
		case '':
			errormsg = "Please choose your preferred method of contact.";
			setErrorMsg(errormsg);
			return false;
		default:
		 return false;
	}
}	
function setErrorMsg(errormsg) {
		$('#step_1 h3').append("<div id='message'></div>");  
		$('#message').html("<h4 style=\"color:red\">" + errormsg + "</h2>")
	}

/**** Talk To Agent Form Subission ****/
function sendAgent() {

  if(checkForm()) {

	  // Cross domain 
	var dataString = "first_name=" + $("#first_name").val() + "&last_name=" + $("#last_name").val() + "&contactMethod=" + $("#contactMethod").val() + "&contactMethod_phone=" + $("#contactMethod_phone").val() + "&contactMethod_phone_time=" + $("#contactMethod_phone_time").val() + "&email_address=" + $("#email_address").val() + "&address_1=" + $("#address_1").val() + "&address_2=" + $("#address_2").val() + "&city=" + $("#city").val() + "&state=" + $("#state").val() + "&zip=" + $("#zip").val()
 
 var url = "http://www.amfamdb.com/drg/dumpcontact.php?" + dataString;

	 $.getJSON(url + "&jsoncallback=?", function(data){
																			 
    Name = data.Name;
    Email = data.Email;
		
    if(Name != "" && Email!= "") {
			sendAgentEmail();
      $("#agent").css('display','none');
      $("#sub_header").html("<h1><span>" + msg + "</span></h1><p>Your comments have been submitted.</p>");
    } else {
    $('##agent').append("<div id='message'></div>");  
     $('#message').html("<h2>Please verify your responses.</h2>").hide().fadeIn(1500).fadeOut(1500, function() {});   
    }
   })
  return false;
	}
	}

function sendAgentEmail() {

	story = $("#story").val()
	    var strA = " ";
			var strB = "%20";
	    while ( story.indexOf(strA) != -1) {
        story = story.replace(strA,strB);
      }
	var dataString = "todo=agent&first_name=" + $("#first_name").val() + "&last_name=" + $("#last_name").val() + "&contactMethod=" + $("#contactMethod").val() + "&contactMethod_phone=" + $("#contactMethod_phone").val() + "&contactMethod_phone_time=" + $("#contactMethod_phone_time").val() + "&email_address=" + $("#email_address").val() + "&address_1=" + $("#address_1").val() + "&address_2=" + $("#address_2").val() + "&city=" + $("#city").val() + "&state=" + $("#state").val() + "&zip=" + $("#zip").val() + "&story=" + story;

	$.ajax({
		type:"POST",
		url: "_assets/asp/agentcontact.asp",
		dataType: "application/x-www-form-urlencoded",
		data: dataString,
		async: false,
		success: function(msg){ $("#agent").css('display','none');
                         $("#sub_header").html("<h1><span>" + msg + "</span></h1><p>Your comments have been submitted.</p>");}
	  })
}

/****  Amfam Product Info Form Submission ****/
function sendProduct() {

  if(checkForm()) {

	  // Cross domain 		
	var dataString = "first_name=" + $("#first_name").val() + "&last_name=" + $("#last_name").val() + "&contactMethod=" + $("#contactMethod").val() + "&contactMethod_phone=" + $("#contactMethod_phone").val() + "&contactMethod_phone_time=" + $("#contactMethod_phone_time").val() + "&email_address=" + $("#email_address").val() + "&address_1=" + $("#address_1").val() + "&address_2=" + $("#address_2").val() + "&city=" + $("#city").val() + "&state=" + $("#state").val() + "&zip=" + $("#zip").val()
 
 var url = "http://www.amfamdb.com/drg/dumpcontact.php?" + dataString;

	 $.getJSON(url + "&jsoncallback=?", function(data){
																			 
    Name = data.Name;
    Email = data.Email;
		
    if(Name != "" && Email!= "") {
			sendProductEmail();
      $("#agent").css('display','none');
      $("#sub_header").html("<h1><span>" + msg + "</span></h1><p>Your request for product information has been received. An representative will use the contact information you provided to deleiver the requested information</p>");
    } else {
    $('##agent').append("<div id='message'></div>");  
     $('#message').html("<h2>Please verify your responses.</h2>").hide().fadeIn(1500).fadeOut(1500, function() {});   
    }
   })
  return false;
	}
}

function sendProductEmail() {

	var products = ""
	if($('.auto').hasClass('selected')) {products = 'auto, ';}
	if($('.home').hasClass('selected')) {products = products + 'home, ';}
	if($('.umbrella').hasClass('selected')) {products = products + 'umbrella, ';}
	if($('.health').hasClass('selected')) {products = products + ' health, ';}
	if($('.life').hasClass('selected')) {products = products + 'life, ';}
	if($('.business').hasClass('selected')) {products = products + 'business, ';}
	if($('.farm').hasClass('selected')) {products = products + 'farm, ';}
	if($('.retirement').hasClass('selected')) {products = products + 'retirement, ';}
  // Replace white space with url encoded %20 for email   
	var strA = " ";
	var strB = "%20";
	while ( products.indexOf(strA) != -1) {
  	products = products.replace(strA,strB);
  }
		
   var dataString = "todo=product&first_name=" + $("#first_name").val() + "&last_name=" + $("#last_name").val() + "&contactMethod=" + $("#contactMethod").val() + "&contactMethod_phone=" + $("#contactMethod_phone").val() + "&contactMethod_phone_time=" + $("#contactMethod_phone_time").val() + "&email_address=" + $("#email_address").val() + "&address_1=" + $("#address_1").val() + "&address_2=" + $("#address_2").val() + "&city=" + $("#city").val() + "&state=" + $("#state").val() + "&zip=" + $("#zip").val() + "&products=" + products;

	$.ajax({
		type:"POST",
		url: "_assets/asp/productinfo.asp",
		dataType: "application/x-www-form-urlencoded",
		data: dataString,
		async: false,
		success: function(msg){ $("#product").css('display','none');
                         $("#sub_header").html("<h1><span>" + msg + "</span></h1><p>Your request for product information has been received. An representative will use the contact information you provided to deleiver the requested information.</p>");}
	  })
		return false
}
