

$(function(){
		// Define some Vars to make life easier
		var fname = $('input[name=firstname]'),
			sname = $('input[name=surname]'),
			name = $('input[name=cm-name]');
		// When we type or take away focus from either name inputs we need to put this into the hidden field
		$('input[name=firstname], input[name=surname]').blur(function(){
			name.val(fname.val()+" "+sname.val());
		}).keyup(function(){
			name.val(fname.val()+" "+sname.val());
	});
});


/**
 * Email validator
 * LEAVE THIS ALONE!!
 * @param str
 * @return
 */
function validateEmail(str) 
{
	var at="@";
	var dot=".";
	var lat=str.indexOf(at);
	var lstr=str.length;
	var ldot=str.indexOf(dot);
	if(str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr){
		return false;
	}
	if(str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr){
		return false;
	}
	if(str.indexOf(at,(lat+1))!=-1){
		return false;
	}
	if(str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot){
		return false;
	}
	if(str.indexOf(dot,(lat+2))==-1){
		return false;
	}
	if(str.indexOf(" ")!=-1){
		return false;
	}
	return true;		
}


$(function(){
	$('#prizeDraw').submit(function(){
		// Assume we are ready
		var ready = true;
		// Define some Vars to make life easier
		var fname = $('input[name=firstname]'),
			sname = $('input[name=surname]'),
			name = $('input[name=cm-name]');
		// Make sure name value isn't blank
		$('input[name=firstname], input[name=surname]').blur(function(){
			name.val(fname.val()+" "+sname.val());
		});
		
		// Cycle through each of the input fields
		$('input.required').each(function(index){
			
			// If this input is blank
			if($(this).val() == ""){
				// Set ready to false
				ready = false;
				
				// Highlight the field with an error class (this can have a border colour of red)
				$(this).addClass('error');

				
			}else{
				// Otherwise do nothing as we are assuming ready and don't want to reset it
				
				// Make sure we remove any error classes
				$(this).removeClass('error');
			}
		});
		
		// We need to check for a valid email address
		if(ready == true){
			
			// Pass the email address to the valid email checking thingy
			if(validateEmail($('input#email').val()) == true){
				// Has passed don't do anything
				
				// Make sure we remove any error classes
				$('input#email').removeClass('error');
				
			}else{
				ready = false;
				
				// Highlight the field with an error class (this can have a border colour of red)
				$('input#email').addClass('error');
			}
		}
		
		if(ready == true){
			
			// Allow the form to submit
			return true;
			
			
		}else{
			// Alert user and don't let the form submit
			alert('Please fill in all your details and ensure you have entered a valid email address');
			// Return false
			return false;
		}
	});
});
