//--------------------------------------------------------------------------------
//
//  frontend.js
//
//  This file contains all JavaScript for the Home Maid website frontend
//
//  Relies on jQuery 1.6.2
//
//  @author		Gerrit Bertier (gerrit.bertier@be.accent.jobs)
//  @copyright	Copyright (c) 2011 - Home Maid
//
//--------------------------------------------------------------------------------

//----------------------------------------
//  The code scope
//----------------------------------------
var homemaid;
if (!homemaid)
{
    homemaid = {};
}
else if (typeof homemaid != 'object')
{
    throw new Error("'homemaid' already exists and is not an object");
}

if (!homemaid.website)
{
    homemaid.website = {};
}
else if (typeof homemaid.website != 'object')
{
    throw new Error("'homemaid.website' already exists and is not an object");
}

if (!homemaid.website.frontend)
{
    homemaid.website.frontend = {};
}
else if (typeof homemaid.website.frontend != 'object')
{
    throw new Error("'homemaid.website.frontend' already exists and is not an object");
}

//----------------------------------------
//  All website frontend code
//----------------------------------------
homemaid.website.frontend =
{
	/**
	 * Properties
	 */
	hasFocus: true,
	
	/**
	 * Initialize the frontend script.
	 *
	 * @author	Gerrit Bertier
	 * @version	1.0
	 */
	init: function()
	{
		// Layout fixes
		this.layout.init();
				
		// Forms
		if ($('form').length > 0)
		{
			this.forms.init();
		}
	},
	
	//----------------------------------------
	//  Layout fixes
	//----------------------------------------
	layout:
	{
		/**
		 * Initialize the layout related code
		 * 
		 * @author	Gerrit Bertier
		 * @version	1.0
		 */
		init: function()
		{
			// Fix content & sidebar height
			this.fixContentHeight();
		},
		
		/**
		 * Fix the sidebar & content height
		 *
		 * @author	Gerrit Bertier
		 * @version	1.0
		 */
		fixContentHeight: function()
		{
			// Fix sidebar and content height issue (if needed)
			if ($('aside').length > 0 && $('#content').length > 0)
			{
				// Find out the absolute y-position & height of both
				var asideY = $('aside').offset().top;
				var asideHeight = $('aside').outerHeight(true);
				var contentY = $('#content').offset().top;
				var contentHeight = $('#content').outerHeight();
				var asideBottomMargin = parseInt($('aside').css('margin-bottom'));
				
				// Find out the bottom y-coordinate of both
				var asideBottom = asideY + asideHeight;
				var contentBottom = contentY + contentHeight;
				
				// Change height to whatever is needed
				if (asideBottom > contentBottom)
				{
					$('#content').height(asideHeight - (asideY - contentY) - asideBottomMargin);
				}
				else
				{
					$('#content').height('auto');
				}
			}
		}
	},
	
	//----------------------------------------
	//  Forms related code
	//----------------------------------------
	forms:
	{
		/**
		 * Initialize the forms.
		 *
		 * @author	Gerrit Bertier
		 * @version	1.0
		 */
		init: function()
		{
			// Check whether the autofocus property is supported, if not, set autofocus using JS
			if (!('autofocus' in document.createElement('input')))
			{
				// Set focus where needed
				$('form input').each(function(index)
				{
					// Set focus (if needed)
					if ($(this).hasAttr('autofocus'))
					{
						$(this).focus();
					}
				});
			}
			
			// Set required field
			$('form input').each(function(index)
			{
				// Add a * to the required field placeholders
				if ($(this).hasAttr('required'))
				{
					var phValue = $(this).attr('placeholder');
					$(this).attr('placeholder', phValue + '*');
				}
				
				var isLastInput = (index == ($('form input').length - 1));
				if (isLastInput)
				{
					$(' [placeholder] ').defaultValue();
				}
			});
		
			// Init the correct form
			if ($('#form-customer').length > 0)
			{
				this.initCustomerForm();		
			}
			
			if ($('#form-employee').length > 0)
			{
				this.initEmployeeForm();
			}
		},
		
		/**
		 * Initialize the customer form.
		 *
		 * @author	Gerrit Bertier
		 * @version	1.0
		 */
		initCustomerForm: function()
		{	
			// Get the correct properties		
			var form = $('#form-customer');
			var errorMessages =
			{
				name: 'Vul uw naam in.',
				email: 'Ongeldig e-mail adres.',
				phone: 'Vul een geldig telefoonnummer in.',
                address: 'Vul uw adres in.',
                areacode: 'Vul uw postcode in.',
                city: 'Vul uw gemeente in.'
			}
			
			// Initialize the form
			this.initForm(form, errorMessages);
		},
		
		/**
		 * Initialize the employee form.
		 *
		 * @author	Gerrit Bertier
		 * @version	1.0
		 */
		initEmployeeForm: function()
		{	
			// Get the correct properties		
			var form = $('#form-employee');
			var errorMessages =
			{
				name: 'Vul uw naam in.',
				email: 'Ongeldig e-mail adres.',
				phone: 'Vul een geldig telefoonnummer in.',
               	address: 'Vul uw adres in.',
                areacode: 'Vul uw postcode in.',
                city: 'Vul uw gemeente in.'
			}
			
			// Initialize the form
			this.initForm(form, errorMessages);
		},
		
		/**
		 * Initialize a form.
		 *
		 * @param form The form to initialize.
		 * @param errorMessages An object containing any possible error messages for the form.
		 *
		 * @author	Gerrit Bertier
		 * @version	1.0
		 */
		initForm: function(form, errorMessages)
		{
			// Get the form elements
			var formElements = form.find('input[type!="submit"],textarea');
			
			// Check if success message is shown
			if ($('.success').length > 0)
			{
				// Close
				$('.success').pause(4000).slideUp(200, function()
				{
					// Set layout
					homemaid.website.frontend.layout.fixContentHeight();
					
					// Empty the feedback
				    $('#feedback').html('');
				});
			}
			
			form.find('input[type!="submit"],textarea').keypress(function()
			{
				if ($(this).hasClass('invalid')) $(this).removeClass('invalid');
			});
			
			// Wait for the user to click the submit button
			$(form).submit(function()
			{
				// Empty the feedback
				$('#feedback').html('');
				
				// Properties
				var formOk = true;
				var errors = [];
				var itemName;
				var itemNameUC;
				var itemValue;
				var itemType;
				var itemIsRequired;
				var itemPlaceholderText;
				
				// Validate form
				formElements.each(function()
				{
					// Set properties
					item = $(this);
					itemName = this.name;
					itemValue = this.value;
					itemType = this.getAttribute('type');
					itemIsRequired = this.getAttribute('required');
					itemPlaceholderText = this.getAttribute('placeholder');
					
					// Check validity
					if ((this.validity) && !this.validity.valid)
					{
						// Set focus (if still needed)
						if (formOk) this.focus();
						
						// Set form invalid
						formOk = false;
						
						// Check if a value is missing 
					    if (this.validity.valueMissing)
					    {
					    	errors.push(errorMessages[itemName]);
					    }
					    else if (this.validity.typeMismatch && itemType == 'email')
					    {
					    	// Fout e-mail veld
					    	errors.push(errorMessages[itemName]);
					    }
						
						// Add 'invalid' class to invalid fields
						if (!item.hasClass('invalid')) item.addClass('invalid');
					}
					
					// Check if this is a required element
					if (itemIsRequired)
					{
						// If HTML5 input required attribute is not supported
						if (!('required' in document.createElement('input')))
						{
							if (itemValue == itemPlaceholderText)
							{
								// Set focus (if still needed)
								if (formOk) this.focus();
								
								// Set form OK flag
								formOk = false;
					        	
					        	// Add the error
								errors.push(errorMessages[itemName]);
					        	
					        	// Add 'invalid' class to invalid fields
					        	if (!item.hasClass('invalid')) item.addClass('invalid');
					        }
					    }
					}
					
					// If HTML5 input email input is not supported  
					if (itemType == 'email')
					{
						// Check if browser supports email field
						var inputElem = document.createElement('input');
						inputElem.setAttribute('type', 'email');
						
						if (inputElem.type != 'email')
						{
							// E-mail regex
							var emailRegEx = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
							
							// Check e-mail validity
							if (!emailRegEx.test(itemValue))
							{
								// Set focus (if still needed)
								if (formOk) this.focus();
					            
					            // Set form OK flag
					            formOk = false;
					            
					            // Add the error
					            errors.push(errorMessages[itemName]);  
					        	
					        	// Add 'invalid' class to invalid fields
					        	if (!item.hasClass('invalid')) item.addClass('invalid');
					        }  
					    }  
					}
					
					// Check area code
					if (itemName == 'areacode')
					{
						// Regex
						var pcRegEx = /^\d{4}$/;
						
						// Check area code validity
						if (itemValue != itemPlaceholderText && itemValue != "" && !pcRegEx.test(itemValue))
						{
							// Set focus (if still needed)
							if (formOk) this.focus();
						    
						    // Set form OK flag
						    formOk = false;
						    
						    // Add the error
						    errors.push(errorMessages[itemName]);  
							
							// Add 'invalid' class to invalid fields
							if (!item.hasClass('invalid')) item.addClass('invalid');
						}
					}
					
					// Empty properties
					itemName = '';
					itemNameUC = '';
					itemValue = '';
					itemType = '';
					itemIsRequired = false;
					itemPlaceholderText = '';
				});
				
				// Attempt to submit the form
				homemaid.website.frontend.forms.attemptSubmit(formOk, form, errors);
				
				// Prevent default form submission (AJAX will handle the call)
				return false;
			});
		},
		
		/**
		 * Attempt to submit the form.
		 * 
		 * @param formOk A boolean value which indicates whether the form is valid for submission (true) or not (false).
		 * @param form The form to send.
		 * @param errors An array containing any error messages to be shown.
		 *
		 * @author	Gerrit Bertier
		 * @version	1.0
		 */
		attemptSubmit: function(formOk, form, errors)
		{
			// Show errors or make the AJAX call to submit the form
			if (formOk)
			{
				// Do an AJAX call to submit the form
				$.ajax(
				{  
				    url: form.attr('action'),
					type: form.attr('method'),
					data: form.serialize() + '&callback=?',
					success: function(data)
					{
						// Track GA goal
						var goalUrl = '';
						if ($(form).attr('id') == 'form-employee')
						{
							goalUrl = '/registreer/huishoudster';
						}
						else if ($(form).attr('id') == 'form-customer')
						{
							goalUrl = '/registreer/prospect';
						}
						_gaq.push(['_trackPageview', goalUrl]);
						
						// Add success message
						$('#feedback').html('<p class="success">Bedankt voor uw aanvraag, we contacteren u zo snel mogelijk.</p>');
						
						// Fade in & out the success message
						$('.success').css('display', 'none');
						$('.success').slideDown(200, function()
						{
							// Set layout
							homemaid.website.frontend.layout.fixContentHeight();
							
							// Slide
							$('.success').pause(4000).slideUp(200, function()
							{
								// Set layout
								homemaid.website.frontend.layout.fixContentHeight();
								
								// Empty the feedback
							    $('#feedback').html('');
							});
						});
						
						// Reset the form
						form.get(0).reset();
				    }
				});
			}
			else
			{
				var errorHtml =	'<ul class="errors">'
				errorHtml += '<li class="info">We konden je aanvraag niet versturen:</li>'
				for (err in errors)
				{  
					errorHtml += ('<li>' + errors[err] + '</li>');
				}
				errorHtml += '</ul>';
				
				// Set the feedback
				$('#feedback').html(errorHtml);
				
				// Show the feedback
				$('.errors').css('display', 'none');
				$('.errors').slideDown(200, function()
				{
					// Set layout
					homemaid.website.frontend.layout.fixContentHeight();
				});
			}
		}
		
	}
}

//----------------------------------------
//  DOM ready
//----------------------------------------

$(document).ready(function()
{
	// Initialize
	homemaid.website.frontend.init();
});

//----------------------------------------
//  jQuery & JavaScript extension
//----------------------------------------

/**
 * Add a hasAttr function to jQuery objects which is capable of checking whether an object has a certain attribute or not.
 *
 * @return Returns true if the attribute is present, false if not.
 *
 * @author	Gerrit Bertier
 * @version	1.0
 */
$.fn.hasAttr = function(name)
{  
   return this.attr(name) !== undefined;
};

/**
 * Add a pause before animating another effect
 *
 * @return Returns the object to animate.
 *
 * @author	Gerrit Bertier
 * @version	1.0
 */
$.fn.pause = function(duration)
{
    $(this).animate({ dummy: 1 }, duration);
    return this;
};
