
// Show the error dialog box and reset the form properly
function showErrorDialogWithMessage(message) 
{
	$('#dialog-message').html(message);
	$('#form-error-dialog').dialog('open');
	$('#donate-submit-button').removeAttr("disabled");
	$('#donate-submit-button').removeClass("disabled");
	$('#submit-button-li').removeClass("hide");
	$('#spinner').addClass("hide");
};




$(document).ready(function() {
	//		DublinDogFoundation Donation Javascript Controller
	//		Dependencies: jQuery 1.5, jQuery UI
	//		This script manages page effects and form validation/collection.
	//		Code copyright 2011, Bryan D K Jones. All rights reserved.

	
	
	// Progressive Enhancement: hide the no-javascript message and display the form
	$('#contribute-no-javascript').addClass("hide");
	$('#donation-form').removeClass("hide");
	
	
	// Enable "_blank" functionality
	$('a.new-window-link').attr("target", "_blank");
	
	
	
	/*Dialogs
	-----------------------------------------------------------------------------------------------*/
			
			$("#form-error-dialog").dialog({
						autoOpen: false,
						modal: true,
						width: 400,
						buttons: {
							Ok: function() {
								$(this).dialog('close');
							}
						}
			});
			
			
			$("#security-code-dialog").dialog({
						autoOpen: false,
						modal: true,
						width: 400,
						buttons: {
							Ok: function() {
								$(this).dialog('close');
							}
						}
			});
	
	
	
	// Show security code info
	$('#security-code-link').click(function() 
	{
		$('#security-code-dialog').dialog('open');
	});
	
	
	
	// Remove placeholder text from phone number box
	$('#phone-number').click(function() 
	{
			if ( $(this).hasClass("phone-placeholder") ) 
			{
				$(this).removeClass("phone-placeholder");
				$(this).val("");
				$(this).css("color", "#2b1903");
			}
	});

	
	

	
	
/* Heavy Lifting: Validate the form and call the server
------------------------------------------------------------------------------------------------------- */



// FOR THE DONATION FORM:

	$('#donate-submit-button').click(function() 
	{	
			//immediately disable the button to prevent double submits
			$(this).attr("disabled", "disabled");
			$(this).addClass("disabled");
			$('#submit-button-li').addClass("hide");
			$('#spinner').removeClass("hide");
			
			
			// First name: make sure it's not blank
			if( $("#first-name").val() == "") 
			{
				showErrorDialogWithMessage("<span class='ui-icon ui-icon-alert' style='float:left; margin:0 7px 50px 0;'></span> Hey! We gotta know who you are! Please enter your <strong>first name</strong>.");
				return;
			}			
			
			// Last Name: make sure it's not blank
			if( $("#last-name").val() == "") 
			{
				showErrorDialogWithMessage("<span class='ui-icon ui-icon-alert' style='float:left; margin:0 7px 50px 0;'></span> Hey! We gotta know who you are! Please enter your <strong>last name</strong>.");
				return;
			}
			
			// Validate Email Address
			var email = $('#email').val();	
			var filter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
			
			if ( email == "") 
			{
				showErrorDialogWithMessage("<span class='ui-icon ui-icon-alert' style='float:left; margin:0 7px 50px 0;'></span> Whoops, you missed one! Please enter your <strong>email address</strong>.");
				return;
			} 
			else if (!filter.test(email)) 
			{
				showErrorDialogWithMessage("<span class='ui-icon ui-icon-alert' style='float:left; margin:0 7px 50px 0;'></span> Sorry, your email address doesn't seem valid. Please make sure you've typed it correctly. (An example of correct formatting is: john@mac.com)");
				return;
			}
			
			
			// Validate Donation amount -- it must be of numerical form XXX.XX
			var donation = $('#donation-amount').val();
			var filter = /^(\d{1,3}(\,\d{3})*|(\d+))(\.\d{2})?$/;
			
			if ( donation == "" ) 
			{
				showErrorDialogWithMessage("<span class='ui-icon ui-icon-alert' style='float:left; margin:0 7px 50px 0;'></span> You forgot to tell us how much you want to donate! Please fill out the <strong>donation amount field</strong>.");
				return;
			} 
			else if (!filter.test(donation)) 
			{
				showErrorDialogWithMessage("<span class='ui-icon ui-icon-alert' style='float:left; margin:0 7px 50px 0;'></span> Sorry, but the donation amount you entered is formatted incorrectly. Please double check the <strong>donation amount field</strong>. It should be in the format '20' or '20.00'");
				return;
			}
			
			
			// Validate the credit card type and number together
			var cardType = $('#card-type').val();
			var cardFilter;
			
			if (cardType == "visa") 
			{
				cardFilter =  /^4[0-9]{12}(?:[0-9]{3})?$/; 		// All Visas start with a 4. New cards have 16 digits. Old cards have 13.
			} 
			else if (cardType == "mastercard") 
			{
				cardFilter = /^5[1-5][0-9]{14}$/; 				// All MasterCards start with the numbers 51 through 55. All have 16 digits.
			}
			else if (cardType == "discover") 
			{
				cardFilter = /^6(?:011|5[0-9]{2})[0-9]{12}$/;	// Discover card numbers begin with 6011 or 65. All have 16 digits.
			} 
			else if (cardType == "amex") 
			{
				cardFilter = /^3[47][0-9]{13}$/;				// American Express card numbers start with 34 or 37 and have 15 digits.
			}
			
			var cardNumber = $('#card-number').val();
						
			// Strip out spaces and dashes
			var cleanCardNumber = cardNumber.replace(/[ -]+/, "");
			
			if (cleanCardNumber == "") 
			{
				showErrorDialogWithMessage("<span class='ui-icon ui-icon-alert' style='float:left; margin:0 7px 50px 0;'></span> Whoops! You missed one! Please fill out the <strong>card number field</strong>.");
				return;
			} 
			else if (!cardFilter.test(cleanCardNumber)) 
			{
				showErrorDialogWithMessage("<span class='ui-icon ui-icon-alert' style='float:left; margin:0 7px 50px 0;'></span> Whoops! The credit card number you entered is either incorrect, or doesn't match the type of card you selected. Please double check these fields and try again.");
				return;
			}

			
			// No way to check expiration date
			
			
			// Exact card name: make sure it's not blank
			if( $("#card-exact-name").val() == "") 
			{
				showErrorDialogWithMessage("<span class='ui-icon ui-icon-alert' style='float:left; margin:0 7px 50px 0;'></span> Please enter the exact name that appears on your credit card in the appropriate field; you can't leave that space blank.");
				return;
			}
			

			
			// Check CVV2 number
			var securityCode = $('#card-security-code').val();
			var codeFilter = /(?!000)\d{3,4}$/;					// Any 3 or 4-digit number is allowed
			
			if (securityCode == "") 
			{
				showErrorDialogWithMessage("<span class='ui-icon ui-icon-alert' style='float:left; margin:0 7px 50px 0;'></span> Whoops! You missed one! Please fill out the <strong>security code field</strong>.");
				return;
			} 
			else if (!codeFilter.test(securityCode)) 
			{
				showErrorDialogWithMessage("<span class='ui-icon ui-icon-alert' style='float:left; margin:0 7px 50px 0;'></span> Whoops! The credit card security code you entered is invalid. (It should be a three or four-digit number.) Please double check this field and try again.");
				return;
			}
			
			
			
			// Billing Address: make sure it's not blank
			if( $("#billing-address").val() == "") 
			{
				showErrorDialogWithMessage("<span class='ui-icon ui-icon-alert' style='float:left; margin:0 7px 50px 0;'></span> Whoops! You missed one! Please enter your <strong>billing address</strong>.");
				return;
			}
			
			
			// City: make sure it's not blank
			if( $("#city").val() == "") 
			{
				showErrorDialogWithMessage("<span class='ui-icon ui-icon-alert' style='float:left; margin:0 7px 50px 0;'></span> Whoops! You missed one! Please enter your <strong>city</strong>.");
				return;
			}
			
			
			// State: can be blank if a country other than 'united states' is selected, otherwise cannot be blank
			var state = $('#state').val();
			var country = $('#country').val();

			if ( country == "united states" && state == "" ) 
			{
				showErrorDialogWithMessage("<span class='ui-icon ui-icon-alert' style='float:left; margin:0 7px 50px 0;'></span> Whoops! You missed one! Please select your <strong>state</strong>.");
				return;
			}
			
			
			
			// Validate zip code -- may be in form: 90210 or 90210-4535
			// Do this only for US addresses. Otherwise, just make sure it's not blank.
			var zipcode = $("#zip-code").val();
			var filter = /(^\d{5}$)|(^\d{5}-\d{4}$)/;
			
			if ( zipcode == "") 
			{
				showErrorDialogWithMessage("<span class='ui-icon ui-icon-alert' style='float:left; margin:0 7px 50px 0;'></span> Whoops! You missed one! Please enter your <strong>zip code</strong>.");
				return;
			} 
			else if (country == "united states" && !filter.test(zipcode)) 
			{
				showErrorDialogWithMessage("<span class='ui-icon ui-icon-alert' style='float:left; margin:0 7px 50px 0;'></span> Sorry, your zip code doesn't seem valid. All zip codes must be in the format '12345' or '12345-1234' and cannot contain non-numerical characters. Please check the <strong>zip code field</strong>.");
				return;
			}
			

			// Validate phone number -- Regex allows only 10 digit phone numbers, with extensions (#, ext, ext., extension). No vanity numbers. Seperators can be dashes, spaces, periods. Accepts numbers without spaces, too.
			var phone = $('#phone-number').val();
			
			// If phone number wasn't provided, clear the field:
			if ( phone == "" || phone == "XXX-XXX-XXXX" ) 
			{
				$('#phone-number').val("");
			} 
			else 
			{
				var filter = /^(?:\+?1\s*(?:[.-]\s*)?)?(?:\(\s*([2-9]1[02-9]|[2-9][02-8]1|[2-9][02-8][02-9])\s*\)|([2-9]1[02-9]|[2-9][02-8]1|[2-9][02-8][02-9]))\s*(?:[.-]\s*)?([2-9]1[02-9]|[2-9][02-9]1|[2-9][02-9]{2})\s*(?:[.-]\s*)?([0-9]{4})(?:\s*(?:#|x\.?|ext\.?|extension)\s*(\d+))?$/;

				if (!filter.test(phone)) 
				{
					showErrorDialogWithMessage("<span class='ui-icon ui-icon-alert' style='float:left; margin:0 7px 50px 0;'></span> Sorry, your phone number doesn't seem valid. Please make sure you've included the area code. </br></br> Examples of valid phone numbers include: 919-598-0909, 212.845.3878, 3427845656, 704-676-7823 ext. 342 ");
					return;
				}
			}
			
			
			// ******************************************************************************************************************
			// We passed all the validation tests, so gather the info to put it into the database

			var firstName = $('#first-name').val();
			var lastName = $('#last-name').val();
			var email = $('#email').val();
			
			var donation = $('#donation').val();
			var cardType = $('#card-type').val();
			var cardNumber = $('#card-number').val();
			var expirationMonth = $('#expiration-month').val();
			var expirationYear = $('#expiration-year').val();
			var cardExactName = $('#card-exact-name').val();
			
			var billingAddress = $('#billing-address').val();
			var city = $('#city').val();
			var state = $('#state').val();
			var zipcode = $('#zip-code').val();
			var country = $('#country').val();
			var phoneNumber = $('#phone-number').val();
			
			if ( $('#marketing').is(":checked") ) 
			{
				var marketing = true;
			} 
			else 
			{
				var marketing = false;
			}
			
			
			
			//*****************************
			// DEBUGGING ONLY -- REMOVE THIS SECTION IN PRODUCTION CODE
			//alert("form validated successfully!");
			//*****************************
			
			
			
			//Make the call to the server script to process the order
			$.ajax ({
				type: "POST",
				url: "../server-scripts/donation-handler.php",		//NOTE: This needs to point to your server-side script
				dataType: "json",
				data: {
					'firstName' : firstName, 
					'lastName' : lastName, 
					'email' : email, 
					
					'donation' : donation,
					'cardType' : cardType,
					'cardNumber' : cardNumber,
					'expirationMonth' : expirationMonth,
					'expirationYear' : expirationYear,
					'cardExactName' : cardExactName,
					
					'billingAddress' : billingAddress, 
					'city' : city, 
					'state' : state, 
					'zipcode' : zipcode, 
					'country' : country,
					'phoneNumber' : phoneNumber,
					 
					'marketing' : marketing 
					},
					
				success: function(result) {
					
					if (result.returncode == "success")
					{
						// Animate the success message in
						$('#tab-1').fadeOut(300);
						setTimeout(function() { $('#success-tab').fadeIn('fast') }, 275);
					} 
					else if (result.returncode =="failed") 
					{
						// Notify the user
						showErrorDialogWithMessage("<span class='ui-icon ui-icon-alert' style='float:left; margin:0 7px 50px 0;'></span> We were unable to successfully complete your transaction. Please double check your credit card information or try a different card. If that still doesn't work, <a href='mailto:info@dublindogfoundation.org'>click here to email us</a>.");
					}
				},
				error: function (XMLHttpRequest, textStatus, errorThrown) {
					showErrorDialogWithMessage("<span class='ui-icon ui-icon-alert' style='float:left; margin:0 7px 50px 0;'></span> We apologize, but something went wrong while we were trying to process your donation. Please try again in a few minutes. If it still doesn't work, <a href='mailto:info@dublindogfoundation.org'>click here to email us</a>.");
				}
			});		
	});
	
	
		
});









