//
//
// whh 2019.11.24 _POST to PHP file handling for Forms
// whh this handles all data floow from webpage form to the PHP codes
// whh currently DIDWW.PHP and CONTACTS.PHP
// whh 2020.03.19 all console logs commented out
//

$(function() {

	      console.log("Running - formSubmit.js");

// hide the back button from the contact managementform
document.getElementById("backContact").style.display = "none";

	// Get the form.
	var form = $('#ajax-contact');
	// Get the messages div.
	var formMessages = $('#form-messages');


	// Set up an event listener for the contact form.
	$(form).submit(function(e) {
		// Stop the browser from submitting the form.
		e.preventDefault();


		// Serialize the form data.
		var formData = $(form).serialize();
//console.table(formData);

	// get phone number being used
var destination = document.getElementById("phoneNumber").textContent;
	// console.log (source);
	// Phone Nmber of the phone being used
var phonesNumber = document.getElementById("phoneNumberSource").textContent;

//console.log("phoneNumberSource: " + phonesNumber);

		// Add the source phone number to the formData
    var formData = formData+ "&destination=" + destination + "&phonesNumber=" + phonesNumber;
//console.table(formData);




		// Submit the form using AJAX.
		$.ajax({
			type: 'POST',
			url: $(form).attr('action'),
			data: formData,
			dataType : 'HTML'
		})

		.done(function(response) {
			// Make sure that the formMessages div has the 'success' class.
			$(formMessages).removeClass('error');
			$(formMessages).addClass('success');


			// Set the message text - change .html to .text for text only
			$(formMessages).html(response);

			// this will launch a whole new page and use the HTML codes
			//'success': function(response)
			//      {
			//          $("html").html($("html", response).html());
			//      }
			//$scrollTO("#justSent");



			// Clear the form after each submit
			$('#selected').val('');
			$('#recipient').val('');
			$('#message').val('');
			// $('#firstName').val(''); // since multiple messages can be sent stop the clearing of this field
			// $('#lastName').val(''); // since multiple messages can be sent stop the clearing of this field
			$('#type').val('');
			$('#mail').val('');
			$('#notes').val('');
			$('#contactDelete').val('');




			$([document.documentElement, document.body]).animate({
			    scrollTop: $("#viewSent").offset().top
			}, 1000 );



		})



		.fail(function(data) {
			// Make sure that the formMessages div has the 'error' class.
			$(formMessages).removeClass('success');
			$(formMessages).addClass('error');

			// Set the message text.
			if (data.responseText !== '') {
				$(formMessages).text(data.responseText);
			} else {
				$(formMessages).text('Oops! An error occured and your message could not be sent.');
			}
		});

	});

});
