(function ($) {
	
	

	$( function() {
		
		$('.contact-form').each(function () {
	
			var $this = $(this),
				$teaser = null,
				$errorbox = null,
				$messagebox = null,
				$errors = null,
				$messages = null,
				$inputs = null,
				$buttons = null,
				$form = null,
				$btn_submit = null,
				labels = {},
				checks = null,
				errors = {},
				messages = {},
				clearMessage = null,
				viewMessage = null,
				clearErrors = null,
				viewErrors = null,
				checkInputs = null,
				submitMessage = null,
				$contactus = null,
				$close = null;
			
			
			$teaser = $this;
			$errorbox = $('.errors', $teaser);
			$messagebox = $('.messages', $teaser);
			$errors = $('input[name^="_err_"]', $teaser).add('textarea[name^="_err_"]', $teaser);
			$messages = $('input[name^="_msg_"]', $teaser).add('textarea[name^="_msg_"]', $teaser);
			$inputs = $('input', $teaser).add($('textarea', $teaser));
			$buttons = $('button', $teaser);
			$contactus = $('.contactus', $teaser);
			$close = $('.close', $teaser);
			
			$contactus.click(function() {
				//var $this = $(this);
				$this.stop().hide().addClass('open').fadeIn();
				//$close.show();
				
				return false;
			});
			$close.click(function() {
				//var $this = $(this);
				$this.stop().show().removeClass('open');
				//$contactus.show();
				return false;
			});
			
			$form = $('form', $teaser);
			
			
			$btn_submit = $('.btn-form-submit', $teaser);
			
			
			checks = {
				'rq_msg'	: {
					'required'	: true,
					'notreqif'	: null,
					'match'		: false,
					'trim'		: false
				},
				'rq_name'	: {
					'required'	: true,
					'notreqif'	: null,
					'match'		: /^\s*(.*(?:\S.?){2,}.*)\s*$/,
					'trim'		: true
				},
				'rq_email'	: {
					'required'	: true,
					'notreqif'	: null,
					'match'		: /^\s*([^@\s'"]+@[^@\s'"]+(?:[^@\s'"]+)+)\s*$/,
					'trim'		: true
				},
				'rq_phone'	: {
					'required'	: true,
					'notreqif'	: null,
					'match'		: /^\s*(.*(?:.?\d.?){3,}.*)\s*$/,
					'trim'		: true
				}
			};
			
			
			
			$inputs.each(function () {
				var $this = $(this),
					fieldname = null;
				fieldname = $this.attr('name');
				
				if (!checks[fieldname]) {
					return;
				}
				
				labels[fieldname] = $this.attr('title');
				
				$this.data('data', { 'empty' : true, 'label' : labels[fieldname], 'focus' : false });
			});
			
			$inputs.mouseover(function () {
				var $this = $(this),
					data = null;
				data = $this.data('data');
				if (data.empty && !data.focus) {
					$this.val('');
				}
			});
			
			$inputs.mouseout(function () {
				var $this = $(this),
					data = null;
				data = $this.data('data');
				if (data.empty && !data.focus) {
					$this.val(data.label);
				}
			});
			
			$inputs.focus(function () {
				var $this = $(this),
					data = null;
				
				$this.trigger('mouseover');
				
				data = $this.data('data');
				data.focus = true;
				$this.data('data', data);
			});
			
			$inputs.blur(function () {
				var $this = $(this),
					data = null;
				data = $this.data('data');
				data.focus = false;
				$this.data('data', data);
				
				$this.trigger('mouseout');
			});
			
			$inputs.change(function () {
				var $this = $(this),
					data = null,
					value = null;
				data = $this.data('data');
				
				value = $this.val();
				
				data.empty = (value === '');
				
				$this.data('data', data);
				
			});
			
			errors = {};
			$errors.each(function () {
				var $this = $(this),
					name = null,
					text = null;
				name = $this.attr('name').replace(/^_err_/, '');
				text = $this.val();
				
				errors[name] = text;
			});
			
			messages = {};
			$messages.each(function () {
				var $this = $(this),
					name = null,
					text = null;
				name = $this.attr('name').replace(/^_msg_/, '');
				text = $this.val();
				
				messages[name] = text;
			});
			
			clearMessage = function () {
				$messagebox.html('');
			};
			
			viewMessage = function (key) {
				var msg = messages[key];
				if (!msg) {
					return;
				}
				$messagebox.html(msg);
			};
			
			clearErrors = function () {
				$errorbox.html('');
				$inputs.css({
					'background-image' : 'none'
				});
			};
			
			viewErrors = function (errorfields, validfields) {
				clearErrors();
				
				var text = '',
					_errorfields = {},
					_validfields = {},
					i = 0,
					fieldname = null;
				
				for (i in errorfields) {
					fieldname = errorfields[i];
					_errorfields[fieldname] = true;
					
					text += '<li>' + errors[fieldname] + '</li>';
				}
				
				for (i in validfields) {
					fieldname = validfields[i];
					_validfields[fieldname] = true;
				}
				
				if (text !== '') {
					text = messages.errors + '<ul>' + text + '</ul>';
					$errorbox.html(text);
				}
				
				
				$inputs.each(function () {
					var $this = $(this),
						fieldname = null;
					
					fieldname = $this.attr('name');
					
					if (_validfields[fieldname]) {
						$this.css({
							'background-image'	: 'url("/ccds_library/famfamfam/icons/tick.png")'
						});
					}
					if (_errorfields[fieldname]) {
						$this.css({
							'background-image'	: 'url("/ccds_library/famfamfam/icons/cross.png")'
						});
					}
				});
				
			};
			
			
			checkInputs = function () {
				var checkresults = {},
					values = {},
					allok = true,
					validfields = [],
					errorfields = [],
					fieldname = null,
					valid = null,
					check = null,
					altfield = null,
					altcheck = null;
				
				$inputs.each(function () {
					var $this = $(this),
						data = null,
						fieldname = null,
						check = null,
						value = null,
						valid = null,
						r = null;
					
					
					
					data = $this.data('data');
					
					fieldname = $this.attr('name');
					check = checks[fieldname];
					if (!check) {
						return;
					}
					
					value = $this.val();
					
					if (data.empty) {
						value = '';
					}
					
					if (check.trim) {
						value = value.replace(/^[\s\r\n]*|[\r\n\s]*$/g, '');
					}
					
					values[fieldname] = value;
					
					valid = true;
					
					if (valid && value.length === 0) {
						valid = false;
					}
					
					if (valid && check.match) {
						r = value.match(check.match);
						if (!r) {
							valid = false;
						}
					}
					
					
					checkresults[fieldname] = valid;
					
				});
				
				
				
				for (fieldname in checkresults) {
					valid = checkresults[fieldname];
					
					if (!valid) {
						check = checks[fieldname];
						
						if (!check.required) {
							continue;
						}
						
						altfield = check.notreqif;
						if (!altfield) {
							allok = false;
							errorfields.push(fieldname);
							continue;
						}
						
						altcheck = checkresults[altfield];
						if (!altcheck) {
							allok = false;
							errorfields.push(fieldname);
							continue;
						}
					} else {
						validfields.push(fieldname);
					}
				}
				
				clearMessage();
				viewErrors(errorfields, validfields);
				
				if (allok) {
					viewMessage('sending');
					submitMessage(values);
				}
			};
			
			submitMessage = function (values) {
				
				var formdata = {};
				
				$inputs.each(function () {
					var $this = $(this),
						fieldname = null,
						data = null,
						value = null;
					
					fieldname = $this.attr('name');
					data = $this.data('data');
					
					if (fieldname.match(/_err_/) || fieldname.match(/_err_/)) {
						return;
					}
					
					value = $this.val();
					
					if (data && data.empty) {
						value = '';
					}
					
					formdata[fieldname] = value;
				});
				
				formdata.ajax = true;
				
				$btn_submit.hide();
				var datum = new Date();
				datum = datum.getTime();
				
				window.setTimeout( function() {
					$.ajax({
						'url'		: $form.attr('action')+"?d="+datum,
						'type'		: $form.attr('method'),
						'dataType'	: 'json',
						'data'		: formdata,
						'cache'		: false,
						'success'	: function (result) {
							if (result.ok) {
								viewMessage('success');
								xajax_sessionTracking({
									'label':'kontakt,'+location.pathname,
									'location':location.pathname
								});
							} else {
								viewMessage('errors_' + result.error);
								$btn_submit.show();
							}
						},
						'error'	: function (result) {
							clearMessage();
							viewMessage('errors_ajax');
							$btn_submit.show();
						}
					});
				}, 1000 );
				
			};
			
			$btn_submit.click(function () {
				checkInputs();
				return false;
			});
		});
		
	});
	
}(jQuery));
