(function( $ ) {
	
	function Validator(obj, valid, invalid, rules) {
		this.options = {
			cl: '_red' 
		};
		this.validFunction = valid;
		this.invalidFunction = invalid;
		this.form = obj;
		this.selector = obj.selector;
		this.rules = rules || {};
	}

	Validator.prototype.engage = function() {

		var valid = true;
		var self = this;
		self.removeHints();

		var allInputs = this.form.find('input[type="text"], select, textarea');
		
		allInputs.each(function() {
			if( self.followRules( $(this) ) ){
				valid = false;
				$(self.selector + ' label.' + this.name ).addClass( self.options.cl );
			}
		});

		if(valid){
			self.validFunction();
		}else{
			self.invalidFunction();
		}

	};
	
	Validator.prototype.followRules = function(el) {
		var data = el.data();
		var val = el.val();
		if(data.required && val === "" ){
			return true;
		}
		return false;
	};

	Validator.prototype.removeHints = function() {
		$(this.selector + ' .' + this.options.cl).removeClass( this.options.cl );
	};

	$.fn.validate = function( valid, invalid, rules ) {
		var validator = new Validator($(this), valid, invalid, rules);
		validator.engage();
	};

})( jQuery );

var validConsult = function() {
	$.post('/?_free_estimate=1', $('#feform').serialize(), function(data) {
		window.location.href = "/thank-you/";			
	});
};

var invalid = function() {
	alert("Please fill the required fields");
};

$(function(){

	/** Sidebar form consult **/

	$('#submit').bind('click', function(e) {
		e.preventDefault();
		$('#feform').validate(validConsult, invalid);	
	});

	$('#feform .input, #feform #comment').bind('focus', function(e) {
		var current = $(this).val();
		var def = $(this).data("def");
	
		if(current == def){
			$(this).val("");
		}
	});
	
	$('#feform .input, #feform #comment').bind('focusout', function(e) {
		var curent = $(this).val();
		var def = $(this).data("def");
		
		if(curent == ""){
			$(this).val(def);
		}
	});
	
	
	
});
