/**
 * fd_form
 * desciption:
 *
 *
 * @author communicatie bureau fourdesign_ Menno Tempelaar
 *
 *
 */
	
var fd_form = function (fd, element) {

	var self				= this;
	var instances			= [];
	var settings			= {
		valid: baseUrl + 'source/img/true.png',
		invalid: baseUrl + 'source/img/false.png',
		succes: 'Uw contactformulier is met succes verstuurd.<br />Wij zullen waar nodig zo spoedig mogelijk contact met u opnemen.',
		error:  'Er is een onbekende fout opgetreden. Probeert u het later nog eens of meldt dit naar <a href="mailto:info@spj.nl">info@spj.nl</a>', 
		selectbox: {
			maxHeight: 150
		}
	};

	var _construct = function () {
		new fd_form_instance(self, element);
	};

	var _search = function () {
		$('body').find('form.fd_form').each(function () {
			instances.push(new fd_form_instance(self, this));
		});
	};


	/**
	 *	`Protected` functies
	 */
	this.get = function () {
		return {
			settings: settings
		};
	};

	this.setSucces = function (_set) {
		settings.succes = _set;
	}


	// Eerste functie uitvoeren
	_construct();
	return {
		add: function (form) {
			instances.push(new fd_form_instance(self, form));
			return;
		}
	}
};

/**
 * fd_form
 * desciption:
 *
 *
 * @author communicatie bureau fourdesign_ Menno Tempelaar
 *
 *
 */
var fd_form_instance = function (fd_form, form) {

	var self			= this;
	var hidden			= false;
	var items			= [];
	var validation		= [];
		

	var _construct = function () {
		_setup();
		_validations();
		_watch();
	};

	var _setup = function () {
		if ( $(form).attr('enctype') === undefined || $(form).attr('encoding') === undefined )
			hidden = true;

		if ( $(form).find('.fd_form_succes') )
			fd_form.setSucces($(form).find('.fd_form_succes').html());

		return;
	};

	var _validations = function () {
		validation.push({
			'style':	'filled',
			'object':	'fd_form_validation_filled'
		});
		validation.push({
			'style':	'mail',
			'object':	'fd_form_validation_mail'
		});
	};

	var _watch = function () {
		$(form).find('div').each(function () {
			if ($(this).hasClass('input'))
				items.push(new fd_form_instance_input(self, this));

			if ($(this).hasClass('textarea'))
				items.push(new fd_form_instance_textarea(self, this));
			
			if ($(this).hasClass('select'))
				items.push(new fd_form_instance_select(self, this));
			
			if ($(this).hasClass('date'))
				items.push(new fd_form_instance_date(self, this));

			if ($(this).hasClass('submit'))
				items.push(new fd_form_instance_submit(self, this));
		});
	};

	/**
	 * Protected functions
	 */

	this.get = function () {
		return {
			validations: validation,
			settings: fd_form.get().settings,
			hidden: hidden
		};
	};

	this.submit = function () {
		for ( var i = 0; i < items.length; i++ ) {
			if (items[i].validate !== undefined) {
				if (!items[i].validate()) {
					return false;
				}
			}
		}

		if (hidden) {

			var formData = $(form).serializeArray();
			
			$.ajax({
				type: 'POST',
				url: (($(form).attr('action') != '')? $(form).attr('action') : window.location.href ),
				data: formData,
				dataType: 'json',
				cache: false,
				success: function (data) {
					if (data) {
						_succes();
					} else {
						_error();
					}
				}
			});

		} else {

			/**
			 *	upload progress.
			 */

		}

		return false;
	};

	var _succes = function () {
		for ( var i = 0; i < items.length; i++ ) {
			items[i].hide();
		}
		
		var succes;
		setTimeout(function () {
			succes = $('<div></div>')
				.addClass('succes')
				.html(fd_form.get().settings.succes)
				.appendTo($(form));
		}, 200);
			
		setTimeout(function () {
			$(succes).remove();
			
			for ( var i = 0; i < items.length; i++ ) {
				items[i].reset();
				items[i].show();
			}
		}, 5000);
		return true;
	};

	var _error = function () {
		$(form).html('');
		$('<div></div>')
			.addClass('error')
			.html(fd_form.get().settings.error)
			.appendTo($(form));
		return true;
	};

	_construct();
	return {
		
	};

};


/**
 *	Input types:
 */

/**
 * fd_form
 * desciption:
 *
 *
 * @author communicatie bureau fourdesign_ Menno Tempelaar
 *
 *
 */
var fd_form_instance_input = function (fd_form_instance, object) {

	var self			= this;
	var valid			= [];

	var input, image, label;

	var _construct = function () {
		_setup();
	};

	var _setup = function () {
		input = $(object).find('input');
		image = $(object).find('img');
		label = $(object).find('label');

		_setValidations();
		_events();
	};

	var _setValidations = function () {
		var validations = fd_form_instance.get().validations;
		for ( var i = 0; i < validations.length; i++ )
			if ( $(object).hasClass(validations[i].style) )
				eval('valid.push(new ' + validations[i].object + '(input))');
	};

	var _events = function () {
		$(input).keyup(function () {
			_validate();
		});

		$(input).focus(function () {
			_focus();
		});

		$(input).blur(function () {
			_blur();
		});
	}

	var _validate = function () {
		for ( var i = 0; i < valid.length; i++ ) {
			if (!valid[i].validate()) {
				_invalid();
				return false;
			}
		}

		_valid();
		return true;
	};

	var _valid = function () {
		if (fd_form_instance.get().settings.valid === true) {
			if (image.length == 1) {
				
				var subsource = $(image).attr('src').replace(baseUrl, '');
				var splitter = subsource.split('.');
					source = splitter[0];
				if ( source.substring((source.length - 4), source.length) == 'true' )
					source = source.substring(0, (source.length - 5));
				else if ( source.substring((source.length - 5), source.length) == 'false' )
					source = source.substring(0, (source.length - 6));

			
				$(image).attr({
					src: source + '-true' +'.'+  splitter[1],
					alt: 'valid'
				});
			}
		} else {
			if (image.length == 1) {
				$(image).attr({
					src: fd_form_instance.get().settings.valid,
					alt: 'valid'
				});
			}
		}

		$(input).removeClass('invalid');
		$(input).addClass('valid');
		return;
	};

	var _invalid = function () {
		if (fd_form_instance.get().settings.invalid === true) {
			if (image.length == 1) {

				var subsource = $(image).attr('src').replace(baseUrl, '');
				var splitter = subsource.split('.');
					source = splitter[0];
				if ( source.substring((source.length - 4), source.length) == 'true' )
					source = source.substring(0, (source.length - 5));
				else if ( source.substring((source.length - 5), source.length) == 'false' )
					source = source.substring(0, (source.length - 6));

				$(image).attr({
					src: source + '-false' +'.'+  splitter[1],
					alt: 'invalid'
				});
			}
		} else {
			if (image.length == 1) {
				$(image).attr({
					src: fd_form_instance.get().settings.invalid,
					alt: 'invalid'
				});
			}
		}

		$(input).removeClass('valid');
		$(input).addClass('invalid');
		return;
	};

	var _focus = function () {
		if ($(input).val() == input[0].defaultValue)
			$(input).val('');

		if (!_validate()) {
			$(input).removeClass('blur');
			$(input).addClass('focus');
		} else {
			$(input).removeClass('blur');
			$(input).addClass('focus');
		}
	};

	var _blur = function () {
		if ($(input).val() == '')
			$(input).val(input[0].defaultValue);

		if (!_validate()) {
			$(input).removeClass('focus');
			$(input).addClass('blur');
		} else {
			$(input).removeClass('blur');
			$(input).addClass('focus');
		}
	};

	_construct();
	return {
		validate: function () {
			return _validate();
		}, 
		hide: function () {
			$(object).fadeOut('fast');
		}, 
		show: function () {
			$(object).fadeIn('fast');
		}, 
		reset: function () {
			$(input).val(input[0].defaultValue);
			_blur();
		}
	};
};

/**
 * fd_form_instance_textarea
 * desciption:
 *
 *
 * @author communicatie bureau fourdesign_ Menno Tempelaar
 *
 *
 */
var fd_form_instance_textarea = function (fd_form_instance, object) {

	var self			= this;
	var valid			= [];
	
	var textarea, image, label;

	var _construct = function () {
		_setup();
	};

	var _setup = function () {
		textarea = $(object).find('textarea');
		image = $(object).find('img');
		label = $(object).find('label');

		_setValidations();
		_events();
	};

	var _setValidations = function () {
		var validations = fd_form_instance.get().validations;
		for ( var i = 0; i < validations.length; i++ ) {
			if ( $(object).hasClass(validations[i].style) )
				eval('valid.push(new ' + validations[i].object + '(textarea))');
		}
	};

	var _events = function () {
		$(textarea).keyup(function () {
			_validate();
		});

		$(textarea).focus(function () {
			_focus();
		});

		$(textarea).blur(function () {
			_blur();
		});
	}

	var _validate = function () {
		for ( var i = 0; i < valid.length; i++ ) {
			if (!valid[i].validate()) {
				_invalid();
				return false;
			}
		}

		_valid();
		return true;
	};

	var _valid = function () {
		if (fd_form_instance.get().settings.valid === true) {
			if (image.length == 1) {
				
				var subsource = $(image).attr('src').replace(baseUrl, '');
				var splitter = subsource.split('.');
					source = splitter[0];
				if ( source.substring((source.length - 4), source.length) == 'true' )
					source = source.substring(0, (source.length - 5));
				else if ( source.substring((source.length - 5), source.length) == 'false' )
					source = source.substring(0, (source.length - 6));

				$(image).attr({
					src: source + '-true' +'.'+  splitter[1],
					alt: 'valid'
				});
			}
		} else {
			if (image.length == 1) {
				$(image).attr({
					src: fd_form_instance.get().settings.valid,
					alt: 'valid'
				});
			}
		}

		$(textarea).removeClass('invalid');
		$(textarea).addClass('valid');
		return;
	};

	var _invalid = function () {
		if (fd_form_instance.get().settings.invalid === true) {
			if (image.length == 1) {

				var subsource = $(image).attr('src').replace(baseUrl, '');
				var splitter = subsource.split('.');
					source = splitter[0];
				if ( source.substring((source.length - 4), source.length) == 'true' )
					source = source.substring(0, (source.length - 5));
				else if ( source.substring((source.length - 5), source.length) == 'false' )
					source = source.substring(0, (source.length - 6));

				$(image).attr({
					src: source + '-false' +'.'+  splitter[1],
					alt: 'invalid'
				});
			}
		} else {
			if (image.length == 1) {
				$(image).attr({
					src: fd_form_instance.get().settings.invalid,
					alt: 'invalid'
				});
			}
		}

		$(textarea).removeClass('valid');
		$(textarea).addClass('invalid');
		return;
	};

	var _focus = function () {
		if ($(textarea).val() == textarea[0].defaultValue)
			$(textarea).val('');
		
		if (!_validate()) {
			$(textarea).removeClass('blur');
			$(textarea).addClass('focus');
		} else {
			$(textarea).removeClass('blur');
			$(textarea).addClass('focus');
		}
	};

	var _blur = function () {
		if ($(textarea).val() == '')
			$(textarea).val(textarea[0].defaultValue);
		
		if (!_validate()) {
			$(textarea).removeClass('focus');
			$(textarea).addClass('blur');
		} else {
			$(textarea).removeClass('blur');
			$(textarea).addClass('focus');
		}
	};

	_construct();
	return {
		validate: function () {
			return _validate();
		}, 
		hide: function () {
			$(object).fadeOut('fast');
		}, 
		show: function () {
			$(object).fadeIn('fast');
		}, 
		reset: function () {
			$(textarea).val(textarea[0].defaultValue);
			_blur();
		}
	};
};





/**
 * fd_form_instance_select
 * desciption:
 * Het object voor een select box.
 *
 * @author communicatie bureau fourdesign_ Menno Tempelaar
 */
var fd_form_instance_select = function (fd_form_instance, element) {
	
	var self			= this;
	var valid			= [];
	var old_options		= [];
	var options			= [];
	var state			= false;
	var moving			= false;
	
	var select, image, label, width, height;
	var input, selectbox;
	
	var _construct = function () {
		if (_setup()) {
			
			_render();
			
			_setValidations();
			
			_events();
			
		}
	};
	
	var _setup = function () {
		select	= $(element).find('select');
		$(select).find('option').each(function () {
			old_options.push($(this).clone());
		});
		
		if ($(element).find('img').length != 0)
			$(element).find('img').remove();
		if ($(element).find('label').length != 0)
			$(element).find('label').remove();
		
		if (select.length > 0) {
			var clone	= $(select).clone();
			$(select).remove();
			select		= clone;
			return true;
		}
		
		return false;
	};
	
	var _setValidations = function () {
		var validations = fd_form_instance.get().validations;
		for ( var i = 0; i < validations.length; i++ ) {
			if ( $(element).hasClass(validations[i].style) )
				eval('valid.push(new ' + validations[i].object + '(input))');
		}
	};
	
	var _render = function () {
		
		input = $('<input></input>');
		$(input).attr({
				type: 'text', 
				name: $(select).attr('name'), 
				value: $(old_options[0]).html(), 
				readonly: 'readonly'
			})
			.addClass('select closed blur valid')
			.appendTo($(element));
		
		// De breedte van de input zetten om zo de breedte van de selectbox te bepalen.
		width = $(input).outerWidth();
						
		$('<div class="clear"></div>');
		
		selectbox = $('<div></div>');
		$(selectbox).addClass('selectbox')
			.css({
				width: width + 'px',
				position: 'absolute', 
				maxHeight: fd_form_instance.get().settings.selectbox.maxHeight + 'px',
				overflow: 'auto', 
				marginLeft: $(input).margin().left,
				marginTop: '-6px'
			})
			.appendTo($(element));
			
		if ($.browser.msie && $.browser.version == 7) {
			$(selectbox).css({
				marginLeft: '-' + width + 'px',
				marginTop: $(input).outerHeight() + 'px'
			});
		}
			
		for (var i in old_options) {
			if (i > 0) {
				var span = $('<span></span>');
				$(span).addClass('option')
					.html($(old_options[i]).html())
					.css({
						display: 'block', 
						position: 'relative'
					})
					.appendTo($(selectbox));
				options.push(span);
			}
		}
		
		// De hoogte zetten om de hoogte vast te stellen voor de selectbox.
		height = $(selectbox).height();
		
		$(selectbox).css('height', '0px');
	};
	
	var _events = function () {
		$(input).click(function () {
			_toggle();
		});
		
		for ( var i in options ) {
			$(options[i]).click(function () {
				$(input).val($(this).html());
				_validate();
				_toggle();
			});
		}
	};
	
	var _toggle = function () {
		if (!moving) {
			if (state) {
				_close();
			} else {
				_open();
			}
		}
	};
	
	var _open = function () {
		$(selectbox).animate({
			height: height + 'px'
		}, {
			duration: 500, 
			complete: function () {
				moving = false;
				state = true;
				$(input).removeClass('closed').addClass('open');
			}
		});
	};
	
	var _close = function () {
		$(selectbox).animate({
			height: '0px'
		}, {
			duration: 500, 
			complete: function () {
				moving = false;
				state = false;
				$(input).removeClass('open').addClass('closed');
			}
		});
	};
	
	var _validate = function () {
		for ( var i = 0; i < valid.length; i++ ) {
			if (!valid[i].validate()) {
				_invalid();
				return false;
			}
		}

		_valid();
		return true;
	};
	
	var _valid = function () {
		$(input).removeClass('blur').addClass('focus');
	};
	
	var _invalid = function () {
		$(input).removeClass('focus').addClass('blur');
	};
	
	_construct();
	return {
		validate: function () {
			return _validate();
		}, 
		hide: function () {
			$(element).fadeOut('fast');
		}, 
		show: function () {
			$(element).fadeIn('fast');
		}, 
		reset: function () {
			$(input).val(input[0].defaultValue);
			_invalid();
		}
	};
}





/**
 * fd_form_instance_select
 * desciption:
 * Het object voor een select box.
 *
 * @author communicatie bureau fourdesign_ Menno Tempelaar
 */
var fd_form_instance_date = function (fd_form_instance, object) {
	
	var self			= this;
	var valid			= [];
	
	var input, image;
	
	var _construct = function () {
		_setup();
		_events();
	};
	
	var _setup = function () {
		input	= $(object).find('input');
		image	= $(object).find('img');
	};
	
	var _events = function () {
		$(input).datepicker({
			
		});
	};
	
	_construct();
	return {
		validate: function () {
			return true;
		}, 
		hide: function () {
			$(object).fadeOut('fast');
		}, 
		show: function () {
			$(object).fadeIn('fast');
		}, 
		reset: function () {
			$(input).val(input[0].defaultValue);
		}
	};
};



/**
 * fd_form_instance_submit
 * desciption:
 *
 *
 * @author communicatie bureau fourdesign_ Menno Tempelaar
 *
 *
 */
var fd_form_instance_submit = function (fd_form_instance, object) {

	var button;

	var _construct = function () {
		_setup();
	};

	var _setup = function () {
		button = $(object).find('input');
		
		_events();
	};

	var _events = function () {
		$(button).click(function () {
			fd_form_instance.submit();
			return false;
		});
	};

	_construct();
	return {
		hide: function () {
			$(object).fadeOut('fast');
		}, 
		show: function () {
			$(object).fadeIn('fast');
		}, 
		reset: function () {
			
		}
	};
};



/**
 * Validation types: 
 */

 var fd_form_validation_filled = function (object) {

	var Default;

	 var _construct = function () {
		 _setup();
	 };
	 
	 var _setup = function () {
		if ($(object).is('select')) {
			$(object).find('option:selected').each(function () {
				Default = $(this).val();
			});
		}

		if ($(object).is('input[type="text"]') || $(object).is('textarea')) {
			Default = object[0].defaultValue;
		}
	 };

	var _validate = function () {
		
		if ($(object).val().replace(/^\s*|\s*$/g,'') == '')
			return false;
		
		if ($(object).val() == Default)
			return false;
		
		return true;
	};

	 _construct();
	 return {
		 validate: function () {
			return _validate();
		}
	 };

 };

 
 var fd_form_validation_mail = function (object) {

	 var _construct = function () {

	 };

	var _validate = function () {
		var emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;
        if(!emailReg.test($(object).val()))
			return false;

		return true;
	};

	 _construct();
	 return {
		validate: function () {
			return _validate();
		}
	 };

 };
