$.fn.validateForm = function () {
	
	return this.each(function(){
		var $form = $(this);
		var fields = $form.find('input:text,textarea');
		var submitBtn = $('#sendMsgBtn');
		
		fields.focus(function(){
			var $this = $(this);			
			if ($this.val() == $this.attr('title')) {
				$this.val('').css('border-color','#ddd');
			}			
			$this.next().show();			
		});
		
		fields.blur(function(){
			var $this = $(this);
			if ($this.val() == '') {
				$this.val($this.attr('title')).css('border-color','#eee');
				$this.next().hide();			
			}								
		});
		
		checkLength =  function(text){
			if ( text.length > 1) {
				return true;
			}
			else {
				return false;
			}
		}
		
		validateEmail = function(email) {
			var RegExp = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+[a-zA-Z0-9]{2,4}$/;
			return RegExp.test(email);
		}
		
		checkInput = function (element) {
			var $this = element;
			
			if (checkLength($this.val())) {				
				if ($this.is('#txtEmail')) {
					console.log(validateEmail($this.val()));
					if(validateEmail($this.val())) {
						$this.next().attr('src','images/accept.png');
						$this.data('valid','true');
					}
					else {
						$this.next().attr('src','images/pencil.png');
						$this.data('valid','false');
					}			
				}
				else {
					$this.next().attr('src','images/accept.png');
					$this.data('valid','true');	
				}				
			}			
			else {
				$this.next().attr('src','images/pencil.png');
				$this.data('valid','false');
			}
		}
		
		fields.keyup(function(){
			checkInput($(this)); 
		});
		
		fields.change(function(){
			checkInput($(this));
		});
		
		
		submitBtn.click(function(){
			var formOK = true;
						
			fields.each(function(){
				if (!$(this).data('valid')) {
					$(this).css('border-color','red');
					formOK = false;	
				}
			});
			
			if (formOK) {
				return true;
			}
			else {
				return false;
			}			
		});					
	});
	
};

$(document).ready(function(){
	$('#contactForm').validateForm();
});
