//------------------------------------
//	FORM.JS
//	Author: 	Engage Interactive
//	Requires:	jquery 1.4.2
//	Version:	0.1
//------------------------------------

Cufon.replace('label, button, #callback h3');

$(function(){
//BEGIN jQuery

	//////////////////////////
	// ON LOAD
	
	$('.form_wrapper').addClass('fresh');
	$('.form_wrapper .messages p:not(.wait)').append('<a href="#" class="close">&times;</a>');
	
	//////////////////////////
	// FORM VALUE TITLE SWAP
	
	$('form input[title]:not([value]), form textarea[title]:not([value])').each(function(){
		$(this).attr('value', $(this).attr('title'));
	});
	
	$('form input[title], form textarea[title]').live('focus',function(){
		if($(this).attr('value') == $(this).attr('title')){
			$(this).attr('value', '');
		}
	});
	
	$('form input[title], form textarea[title]').live('blur',function(){
		if($(this).attr('value') == $(this).attr('title') || $(this).attr('value') == ''){
			$(this).attr('value', $(this).attr('title'));
		}
	});	
	
	//////////////////////////
	// VALIDATION

	// SIMPLE TEXT FIELD
	
	$('input[type=text].required, textarea.required').live('blur', function(){
		
		if( $(this).closest('.form_wrapper').hasClass('fresh') == true ) return false;
		
		v = $(this).val();
		l = v.length;
		
		if( l < 3 || v == $(this).attr('title') || $(this).siblings('.counter').hasClass('error') ){
			$(this).error('.field');
		}else{
			$(this).valid('.field');
		}
	});
	
	// SIMPLE DROP DOWN
	
	$('select.required').live('blur', function(){

		if( $(this).closest('.form_wrapper').hasClass('fresh') == true ) return false;

		v = $(this).val();
		
		if( v == $(this).children('option:first').val() || v == $(this).children('option[disabled]').val() ){
			$(this).error('.field');
		}else{
			$(this).valid('.field');
		}
	});
	
	// EMAIL

	$('input[type=text].email').live('blur', function(){

		if( $(this).closest('.form_wrapper').hasClass('fresh') == true ) return false;

		v = $(this).val();
		email = checkemail( v );
		
		if( v != $(this).attr('title') && ( email == false || email == null ) ){
			$(this).error('.field');
		}else if( v != $(this).attr('title') ){
			$(this).valid('.field');
		}else if( v == $(this).attr('title') && !$(this).hasClass('required') ){
			$(this).parent('.field').removeClass('valid').removeClass('error');
		}
	});
	
	// PHONE NUMBER

	$('input[type=text].phone').live('blur', function(){

		if( $(this).closest('.form_wrapper').hasClass('fresh') == true ) return false;

		v = $(this).val();
		pn = checkphone( v );
		mn = checkMphone( v );
		
		if( v != $(this).attr('title') && ( ( pn == false || pn == null ) && ( mn == false || mn == null ) ) ){
			$(this).error('.field');
		}else if( v != $(this).attr('title') ){
			$(this).valid('.field');
		}else if( v == $(this).attr('title') && !$(this).hasClass('required') ){
			$(this).parent('.field').removeClass('valid').removeClass('error');
		}
	});
	
	// CHECKBOXES
	
	$('input[type=checkbox].required').change(function(){
		if( $(this).closest('.form_wrapper').hasClass('fresh') != true ){		
			if( $(this).attr('checked') ){
				$(this).valid('.field');
			}else{
				$(this).error('.field');
			}
		}
	});
	
	// RADIO
	
	$('.radio ul.required input[type=radio]').change(function(){
		if( $(this).closest('.form_wrapper').hasClass('fresh') != true ){
			$(this).valid('.field');
		}
	});
	
	// RADIO
	
	function checkRadio(formID){
		$(formID + ' .radio ul.required').each(function(){
			var count = $(this).find('input[type=radio][checked=true]').length;

			if( count < 1 ){
				$(this).error('.field');
			}else{
				$(this).valid('.field');
			}
		});
		
		$(formID + ' input[type=checkbox].required').each(function(){
			if( !$(this).attr('checked') ) $(this).error('.field');
		});
	}
	
	function checkValidation(formID){

		// Innocent until proven guilty!
		valid = true;

		// Check the required fields
		$(formID + ' .required').blur();
		
		// Check the phone and emails, not necessarily required
		$(formID + ' .phone, ' + formID + ' .email').blur();

		// Check the radios
		checkRadio(formID);

		// Are we validated?
		if( $(formID + ' .error:visible').size() > 0 ){
			valid = false;
		}

		return valid;
	}
	
	$('.form_wrapper button[type=submit]').click(function(e){

		formID = '#' + $(this).closest('.form_wrapper').attr('id');
		
		$(formID).removeClass('fresh');
		
		if($.browser.safari){
			scrollElement = $('body');
		}else{
			scrollElement = $('html');
		}
		
		formOffset = $(formID).offset().top - 20;
		
		if( checkValidation(formID) == true ){
			
			// Clean up uncomplete fields
			$(formID + ' input, ' + formID + ' textarea').each(function(){
				if( $(this).val() == $(this).attr('title') || $(this).val() == '' ){
					$(this).val(' - ');
				}
			});
			
			// Serialise the data
			formData = $(formID).serialize();

			scrollElement.animate({scrollTop:formOffset},500,'easeInOutExpo',function(){
				fadeMsg(formID,'wait',2000,function(){
					
					// Set the height while we piss about with stuff
					$(formID).css({height:$(formID).height()});
					
					// Send the form with ajax
					$.ajax({
						type: 'POST',
						url: $(formID).attr('action'),
						data: formData,
						success: function() {
							$(formID + ' fieldset').fadeOut(function(){
								$(this).remove();
								$(formID + ' .thankyou').fadeIn();
								if( formID == '#callback' ) return false;
								$(formID).animate({height:$(formID + ' .thankyou').outerHeight(true)},1000,'easeInOutExpo');
							});
						}
					});
				});
			});

		}else{			
			scrollElement.animate({scrollTop:formOffset},500,'easeInOutExpo',function(){
				fadeMsg(formID,'error',4000,false,function(){
					fadeMsg(formID,'hide');
				});
			});
		}
		return false;
	});
	
	var cbackTimer = {};
	
	function fadeMsg(id,m,t,before,after){
		
		if(m == 'hide'){
			if( $.browser.msie ){
				$(id + ' .messages').hide();
			}else{
				$(id + ' .messages').stop([]).fadeOut();
			}
		}else{
			$(id + ' .messages').children('.'+m).addClass('active').siblings().removeClass('active');
			
			if( $.browser.msie ){
				$(id + ' .messages').show(0,function(){
					if(before) before.call();
				})
			}else{
				$(id + ' .messages').stop([]).fadeIn(400,function(){
					if(before) before.call();
				})			
			}
			
			cbackTimer = $.timer(t,function(){
				$.clearTimer(cbackTimer);
				if(after) after.call();
			});
		}
	}
	
	$('.messages').click(function(){

		if( $(this).children('p.wait').hasClass('active') == true ) return false;
		
		$.clearTimer(cbackTimer);
		
		if( $.browser.msie ){
			$(this).hide().removeAttr('style');
		}else{
			$(this).stop([]).fadeOut(function(){
				$(this).removeAttr('style');
			});
		}
		return false;
	});
	
	$('.messages .close').live('click',function(){
		
		$.clearTimer(cbackTimer);
		
		if( $.browser.msie ){
			$(this).closest('.messages').hide().removeAttr('style');
		}else{
			$(this).closest('.messages').stop([]).fadeOut(function(){
				$(this).removeAttr('style');
			});
		}
		return false;
	});


//END jQuery
});

//////////////////////////
// REGULAR EXPRESSIONS

// EMAIL

function checkemail(email_address) {
	return email_address.length > 5 && email_address.match(/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/);
}

// PHONE (LANDLINE)

function checkphone(phone_number) {
	return phone_number.length > 9 && phone_number.match(/^(\(?(0|\+44)[1-9]{1}\d{1,4}?\)?\s?\d{3,4}\s?\d{3,4})$/);
}

// PHONE (EMAIL)

function checkMphone(phone_number) {
	return phone_number.length > 9 && phone_number.match(/^((0|\+44)7(5|6|7|8|9){1}\d{2}\s?\d{6})$/);
}


//////////////////////////
// SET VALID OR ERROR

(function($){
	$.fn.valid = function(e) {
		this.closest(e).addClass('valid').removeClass('error');
	};
})(jQuery);

(function($){
	$.fn.error = function(e) {
		this.closest(e).addClass('error').removeClass('valid');
	};
})(jQuery);


//////////////////////////
// EASING

jQuery.extend(jQuery.easing,{
	easeInOutExpo: function(x,t,b,c,d){
		if (t==0) return b;
		if (t==d) return b+c;
		if ((t/=d/2) < 1) return c/2 * Math.pow(2, 10 * (t - 1)) + b;
		return c/2 * (-Math.pow(2, -10 * --t) + 2) + b;
	}
});

//////////////////////////
// TIMERS

jQuery.timer = function(time,func,callback){
	var a = {timer:setTimeout(func,time),callback:null}
	if(typeof(callback) == 'function'){a.callback = callback;}
	return a;
};

jQuery.clearTimer = function(a){
	clearTimeout(a.timer);
	if(typeof(a.callback) == 'function'){a.callback();};
	return this;
};
