function initPage()
{
	clearFormFields({
		clearInputs: true,
		clearTextareas: true,
		passwordFieldText: true,
		addClassFocus: "focus",
		filterClass: "default"
	});
}

function clearFormFields(o)
{
	if (o.clearInputs == null) o.clearInputs = true;
	if (o.clearTextareas == null) o.clearTextareas = true;
	if (o.passwordFieldText == null) o.passwordFieldText = false;
	if (o.addClassFocus == null) o.addClassFocus = false;
	if (!o.filterClass) o.filterClass = "default";
	
	if(o.clearInputs) {
		var inputs = document.getElementsByTagName("input");
		for (var i = 0; i < inputs.length; i++ ) {
			if((inputs[i].type == "text" || inputs[i].type == "password") && inputs[i].className.indexOf(o.filterClass) == -1) {
				inputs[i].valueHtml = inputs[i].value;
				inputs[i].onfocus = function ()	{
					if(this.valueHtml == this.value) this.value = "";
					if(this.fake) {
						inputsSwap(this, this.previousSibling);
						this.previousSibling.focus();
					}
					if(o.addClassFocus && !this.fake) {
						this.className += " " + o.addClassFocus;
						this.parentNode.className += " parent-" + o.addClassFocus;
					}
				}
				inputs[i].onblur = function () {
					if(this.value == "") {
						this.value = this.valueHtml;
						if(o.passwordFieldText && this.type == "password") inputsSwap(this, this.nextSibling);
					}
					if(o.addClassFocus) {
						this.className = this.className.replace(o.addClassFocus, "");
						this.parentNode.className = this.parentNode.className.replace("parent-"+o.addClassFocus, "");
					}
				}
				if(o.passwordFieldText && inputs[i].type == "password") {
					var fakeInput = document.createElement("input");
					fakeInput.type = "text";
					fakeInput.value = inputs[i].value;
					fakeInput.className = inputs[i].className;
					fakeInput.fake = true;
					inputs[i].parentNode.insertBefore(fakeInput, inputs[i].nextSibling);
					inputsSwap(inputs[i], null);
				}
			}
		}
	}
	
	if(o.clearTextareas) {
		var textareas = document.getElementsByTagName("textarea");
		for(var i=0; i<textareas.length; i++) {
			if(textareas[i].className.indexOf(o.filterClass) == -1) {
				textareas[i].valueHtml = textareas[i].value;
				textareas[i].onfocus = function() {
					if(this.value == this.valueHtml) this.value = "";
					if(o.addClassFocus) {
						this.className += " " + o.addClassFocus;
						this.parentNode.className += " parent-" + o.addClassFocus;
					}
				}
				textareas[i].onblur = function() {
					if(this.value == "") this.value = this.valueHtml;
					if(o.addClassFocus) {
						this.className = this.className.replace(o.addClassFocus, "");
						this.parentNode.className = this.parentNode.className.replace("parent-"+o.addClassFocus, "");
					}
				}
			}
		}
	}
	
	function inputsSwap(el, el2) {
		if(el) el.style.display = "none";
		if(el2) el2.style.display = "inline";
	}
}

if (window.addEventListener)
	window.addEventListener("load", initPage, false);
else if (window.attachEvent)
	window.attachEvent("onload", initPage);

var defaultValues = ['Phone', 'First Name', 'Last Name', 'Email', 'Email Address',
	'Street', 'City', 'State', 'Zip', 'Comments', 'How Did you hear about us?',
	'Zip Code']; 

function notDefault(value) {
	if ($.inArray(value, defaultValues) >= 0) return false;
	else return true;
}


$.validator.addMethod("notDefault", function(value, element) { return notDefault(value) }, '');

var submitted = false;

// text inputs only
var defaults = {
	Email: 'Email',
	FirstName: 'First Name',
	LastName: 'Last Name',
	Phone1: 'Phone',
	_Comments: 'Comments',
	_HowYouHeardofGuardian: 'How Did you hear about us?',
	street_address: 'Street',
	StreetAddress1: 'Street',
	State: 'State',
	PostalCode: 'Zip Code',
	City: 'City'
};
		
$(document).ready(function() {
	
	// each() allows to validate correctly multiple forms on page
	$(".form-download").each(function(){
		var form = $(this);
		
		//if (form.hasClass('download-video-form'))
		//	return true;
		
		form.data('start_height', form.find('.step-container:visible').height());
		
		
		// prevent firefox feature when it remembers previously values
		// even after page reload (we need default values)
		$.each(defaults, function(k, v){
			form.find('[name='+k+']').val(v);
		});
				
		form.find('[name=inf_option_RoofingNeeds]').removeAttr('checked');
		
		//
		form.validate({
			focusInvalid: false,
			wrapper: '',//"li",		
			showErrors: function(errorMap, errorList) {
				if (submitted) {
					//var summary = 'You have the following errors: \n';
					//$.each(errorList, function() { summary += " * " + this.message + "\n"; });
					//alert(summary);
					submitted = false;
				}
				this.defaultShowErrors();
			},
			errorPlacement: function(error, element) {
				error.appendTo( element.parentsUntil('form').parent('form').find('.errors-display') );
			},		
			invalidHandler: function(form, validator) {
				//if ((''+window.location).indexOf('debug'))
				//	alert(1);
				submitted = true;
			},
			submitHandler: function(form, validator){
				//signup();
				submitForm($(form));
			},
			rules: {
				FirstName: {required:true, notDefault:true},
				LastName: {required:true, notDefault:true},
				Email: {required:true, notDefault:true, email:true},
				Phone1: {required:true, notDefault:true, minlength:10}
				
				// default value will be replaced by empty value
				,_Comments: {required:false, notDefault:false}
				,_HowYouHeardofGuardian: {required:false, notDefault: false}
				
				,inf_field_FirstName: {required:true, notDefault:true}
				,inf_field_LastName: {required:true, notDefault:true}
				,inf_field_Email: {required:true, notDefault:true, email:true}
				,inf_field_Phone1: {required:true, notDefault:true, minlength:10}
			},
			messages: {
				FirstName: "Please enter your first name",
				LastName: "Please enter your last name",
				Email: "Please enter a valid email",
				Phone1: "Please enter a valid phone number (minimum 10 numbers)"
				
				//,_HowYouHeardofGuardian: "Please tell how did you hear about us"
				
				,inf_field_FirstName: "Please enter your first name"
				,inf_field_LastName: "Please enter your last name"
				,inf_field_Email: "Please enter a valid email"
				,inf_field_Phone1: "Please enter a valid phone number (minimum 10 numbers)"
			}
		});
		
		//form.submit(function(){return false;});
	});	

	/*
	function signup(){
		showLoader($('#home-form'));
		$.ajax({
			type: "POST",
			data: $(".form-download").serialize(),
			url: "/includes/process.php",
			success: function(msg){
				fadeLoader($('#home-form'));
				if(msg == 1) {
					$('.form-download .step1').hide();
					$('.form-download .step2').show();
				}
				else alert('There was an Error Signing Up, Please Try Again!');
			}
		});
	}
	*/
});

function submitForm(form)
{
	var formId = form.attr('id')
		,isSend = false
		;
		
	if (formId.match(/request-inspection-form/))
	{
		isSend = true;
		var currentStep = 1
		if (form.find('.step2:visible').length > 0)
			currentStep = 2;
		if (form.find('.step3:visible').length > 0)
			currentStep = 3;
			
		form.find('[name=step]').val(currentStep);
		
		// preventing posting default values
		if (currentStep == 2)
		{
			$.each(defaults, function(k, v){
				var elm = form.find('[name='+k+']');
				if (elm.length > 0 && elm.val() == v)
					elm.val('');
			});		
		}
	}
	

	if (formId.match(/contact-us-form/))
	{
		var c = form.find('[name=_Comments]');
		if (c.val() == 'Comments')
			c.val('');
		
	
		isSend = true;
		var currentStep = 1
		if (form.find('.step2:visible').length > 0)
			currentStep = 2;
		if (form.find('.step3:visible').length > 0)
			currentStep = 3;
			
		form.find('[name=step]').val(currentStep);
	}	
	
	if (formId.match(/download-form/))
	{
		isSend = true;
		form.get(0).submit();
		return;
	}
	
	/*
	var formClone = form.clone();
	// preventing posting default values
	$.each(defaults, function(k, v){
		var elm = formClone.find('[name='+k+']');
		if (elm.length > 0 && elm.val() == v)
			elm.val('');
	});
	*/
	
	var formData = form.serialize();
	
	
	if (isSend)
	{
		showLoader(form);
		
		$.ajax({
			type: "POST",
			data: formData,
			url: "/includes/process.php",
			success: function(data){
				fadeLoader(form);
				
				//
				if (formId.match(/request-inspection-form/))
				{
					if(data.result == 1) {
						form.find('.step-container').hide();
						
						var curContainer = form.find('.step'+(currentStep < 3 ? currentStep+1 : currentStep));
						
						curContainer.css('height', 'auto').show();
						if (curContainer.height() < form.data('start_height'))
							curContainer.height(form.data('start_height'));
					}
					else alert('There was an Error Signing Up, Please Try Again!');
				
				}
				
				//
				if (formId.match(/contact-us-form/))
				{
					if(data.result == 1) {
						form.find('.step-container').hide();
						
						var curContainer = form.find('.step'+(currentStep < 3 ? currentStep+1 : currentStep));
						
						curContainer.css('height', 'auto').show();
						if (curContainer.height() < form.data('start_height'))
							curContainer.height(form.data('start_height'));
					}
					else
						form.find('.errors-display').html('<div class="error">There was an Error, Please Try Again!</div>');
				}
				
				/*
				if (formId.match(/download-form/))
				{
					if(data.result == 1) {
						form.find('.step-container').hide();
						
						var curContainer = form.find('.step2');
						
						curContainer.css('height', 'auto').show();
						if (curContainer.height() < form.data('start_height'))
							curContainer.height(form.data('start_height'));
					}
					else alert('There was an Error Signing Up, Please Try Again!');
				}
				*/
				
			}
		});
	}
	
}

function formStepBack(btn, toStep)
{
	var form = $(btn).parentsUntil('form').parent('form');
	form.find('.step1, .step2, .step3').hide();
	form.find('.step'+toStep).show();
}


function showLoader(target_obj)
{
	var loader = $('.loader', target_obj), loader_mask = $('.loader_mask', target_obj);
	target_obj.css('position', 'relative');
	
	if (loader.length == 0)
	{
		target_obj.append('<div class="loader" style="display:none"><div class="loader-inner"></div></div>');
		loader = $('.loader', target_obj);
	}
	
	if (loader_mask.length == 0)
	{
		target_obj.append('<div class="loader_mask" style="display:none"></div>');
		loader_mask = $('.loader_mask', target_obj);
	}
		
	loader_mask
		//.fadeTo('fast', '0.4')
		.css({
			'z-index': '9998',
			'height': target_obj.outerHeight(),
			'width': target_obj.outerWidth(),
			'opacity': 0.5
		})
		.show()
		;
		
	loader
		.css({
			'z-index': '9999',
			'top': target_obj.height() / 2 - loader.height() / 2,
			'left': target_obj.width() / 2 - loader.width() / 2
		})
		.show()
		;

}

function fadeLoader(target_obj){
	/*
	$('.loader', target_obj).fadeOut();
	$('.loader', target_obj).queue(function () {
		$('.loader_mask', target_obj).fadeTo('fast', '0').hide();
		 $(this).dequeue();
	});
	*/
	$('.loader', target_obj).hide();
	$('.loader_mask', target_obj).hide();
}

