/*
 * @title		AJAX Pop-Up E-Newsletter Form
 * @author		Daniel Petkovski
 * @project		La Vista Azul
 * @copyright	(c) May 2010
 *
 */

jQuery(function ($) {
	var contact = {
		message: null,
		location: null,
		init: function () {
			$('.newsletter').click(function (e) {
				e.preventDefault();
				
				/*==============================
				  Set Path to Files
				==============================*/
				if ($('#sub-page-active').length > 0) {
					contact.location = '../';
				} else {
					contact.location = '';
				}
				
				/*==============================
				  Load the E-Newsletter Form using AJAX
				==============================*/
				
				var ajaxString = contact.location + 'data/newsletter.php';
				
				$.get(ajaxString, function(data){
					// Create a Modal Dialog with the Data //
					$(data).modal({
						position: ["20px",],
						overlayId: 'contact-overlay',
						containerId: 'contact-container',
						onOpen: contact.open,
						onShow: contact.show,
						onClose: contact.close
					});
				});
			});

			/*==============================
			  Preload Images
			==============================*/
			
			var imgPath = contact.location + 'images/';
			var img = ['button_cancel.png', 'loading_contact.gif', 'button_send.png'];
			$(img).each(function () {
				var i = new Image();
				i.src = imgPath + this;
			});
		},
		open: function (dialog) {
			
			/*==============================
			  Set Default Height
			==============================*/
			
			var h = 285;
			
			/*==============================
			  Handle Browser Specific Mods
			==============================*/
			
			// Firefox Fixes //
			if ($.browser.mozilla) {
				$('#contact-container .contact-button').css({
					'padding-bottom': '2px'
				});
				
				// Set Height //
				h = 285;
			}
			// Safari Fixes //
			if ($.browser.safari) {
				// Set Height //
				h = 285;
			}
			// Internet Explorer //
			if ($.browser.msie) {
				$('#contact-container .contact-button').css({
					'margin-top' : '10px'														 
				});
				$('#contact-container fieldset').css({
					'position' : 'relative',
					'margin' : '25px 0px',
					'padding-top' : '10px'
				});
				$('#contact-container legend').css({
					'position' : 'absolute',
					'top' : '-12px',
					'left' : '2px'
				});
				$('#contact-container #fix-fieldset').css({
					'margin-top' : '10px'
				});
				$('#contact-container .contact-note').css({
					'margin-top' : '15px'
				});
				
				// Set Height //
				h = 285;
			}
			
			
			/*==============================
			  Animate and Open Form Modal
			==============================*/
			
			var title = $('#contact-container .contact-title').html();
			$('#contact-container .contact-title').html('Loading E-Newsletter Sign-Up Form...');
			dialog.overlay.fadeIn(200, function () {
				dialog.container.fadeIn(200, function () {
					dialog.data.fadeIn(200, function () {
						$('#contact-container .contact-content').animate({
							height: h
						}, function () {
							$('#contact-container .contact-title').html(title);
							$('#contact-container form').fadeIn(200, function () {
								$('#contact-container #contact-first-name').focus();

								// Fix PNG's for IE 6 //
								if ($.browser.msie && $.browser.version < 7) {
									$('#contact-container .contact-button').each(function () {
										if ($(this).css('backgroundImage').match(/^url[("']+(.*\.png)[)"']+$/i)) {
											var src = RegExp.$1;
											$(this).css({
												backgroundImage: 'none',
												filter: 'progid:DXImageTransform.Microsoft.AlphaImageLoader(src="' +  src + '", sizingMethod="crop")'
											});
										}
									});
								}
							});
						});
					});
				});
			});
		},
		show: function (dialog) {
			
			/*==============================
			  Handle Form Send
			==============================*/
			
			$('#contact-container .contact-send').click(function (e) {
				e.preventDefault();
				
				var sendString = contact.location + 'data/newsletter.php';
				
				// Validate Form //
				if (contact.validate()) { // Form Pass
					var msg = $('#contact-container .contact-message');
					msg.fadeOut(function () {
						msg.removeClass('contact-error').empty();
					});
					$('#contact-container .contact-title').html('Sending Information...');
					$('#contact-container form').fadeOut(200);
					$('#contact-container .contact-content').animate({
						height: '80px'
					}, function () {
						$('#contact-container .contact-loading').fadeIn(200, function () {
							$.ajax({
								url: sendString,
								data: $('#contact-container form').serialize() + '&action=send',
								type: 'post',
								cache: false,
								dataType: 'html',
								success: function (data) {
									$('#contact-container .contact-loading').fadeOut(200, function () {
										$('#contact-container .contact-title').html('E-Newsletter Sign-Up Sent. Thank you!');
										msg.html(data).fadeIn(200);
									});
								},
								error: contact.error
							});
						});
					});
				}
				else { // Form Fail
					if ($('#contact-container .contact-message:visible').length > 0) {
						var msg = $('#contact-container .contact-message div');
						msg.fadeOut(200, function () {
							msg.empty();
							contact.showError();
							msg.fadeIn(200);
						});
					}
					else {
						$('#contact-container .contact-message').animate({
							height: '30px'
						}, contact.showError);
					}
					
				}
			});
		},
		close: function (dialog) {
			$('#contact-container .contact-message').fadeOut();
			$('#contact-container .contact-title').html('Closing E-Newsletter Sign-Up Form...');
			$('#contact-container form').fadeOut(200);
			$('#contact-container .contact-content').animate({
				height: 40
			}, function () {
				dialog.data.fadeOut(200, function () {
					dialog.container.fadeOut(200, function () {
						dialog.overlay.fadeOut(200, function () {
							$.modal.close();
						});
					});
				});
			});
		},
		error: function (xhr) {
			alert(xhr.statusText);
		},
		validate: function () {
			
			contact.message = ''; // Set Error Message to Default
			
			/*==============================
			  Cycle Through Form Elements
			==============================*/
			
			$('input[rel=contact-required], select[rel=contact-required], textarea[rel=contact-required]').each( function () {
				
				// Check if Field is Empty //
				if (!$(this).val()) {
					contact.message = 'Please Complete All Required Fields';
					
					// Add Error Border Depending on Form Object Type //
					if ($(this).is('select')){
						$(this).parent().css('border','1px solid #FF0000');
					} else {
						$(this).css('border-color','#FF0000');
					}
				}
				// If Field NOT Empty AND Email //
				else if ($(this).attr('id') == 'contact-email') {
					
					var email = $(this).val(); // Set Email Value
					
					// Validate Email //
					if (!contact.validateEmail(email)) {
						contact.message = 'Incorrect E-Mail Format';
						$(this).css('border-color','#FF0000');
					}
					else {
						$(this).css('border-color','#888888');
					}
				}
				// Field is Valid - Reset Color //
				else {
					if ($(this).is('select')){
						$(this).parent().css('border','none');
					} else {
						$(this).css('border-color','#888888');
					}
				}
			});
			
			/*==============================
			  Return Pass or Fail
			==============================*/
			
			if (contact.message.length > 0) {
				return false;
			}
			else {
				return true;
			}
		},
		validateEmail: function (email) {
			var at = email.lastIndexOf("@");

			// Make sure the at (@) sybmol exists and  
			// it is not the first or last character
			if (at < 1 || (at + 1) === email.length)
				return false;

			// Make sure there aren't multiple periods together
			if (/(\.{2,})/.test(email))
				return false;

			// Break up the local and domain portions
			var local = email.substring(0, at);
			var domain = email.substring(at + 1);

			// Check lengths
			if (local.length < 1 || local.length > 64 || domain.length < 4 || domain.length > 255)
				return false;

			// Make sure local and domain don't start with or end with a period
			if (/(^\.|\.$)/.test(local) || /(^\.|\.$)/.test(domain))
				return false;

			// Check for quoted-string addresses
			// Since almost anything is allowed in a quoted-string address,
			// we're just going to let them go through
			if (!/^"(.+)"$/.test(local)) {
				// It's a dot-string address...check for valid characters
				if (!/^[-a-zA-Z0-9!#$%*\/?|^{}`~&'+=_\.]*$/.test(local))
					return false;
			}

			// Make sure domain contains only valid characters and at least one period
			if (!/^[-a-zA-Z0-9\.]*$/.test(domain) || domain.indexOf(".") === -1)
				return false;	

			return true;
		},
		showError: function () {
			$('#contact-container .contact-message')
				.html($('<div class="contact-error"></div>').append(contact.message))
				.fadeIn(200);
		}
	};

	contact.init();
});