/*
	PageBuilder Forms Script
	Copyright (c) 2011 Virtual Design House (marketingease.com, pagebuilderplus.com)
*/

// centers over screen
function newWindow(page,name,w,h,features){
	var winl = (window.screen.width-w)/2;
	var wint = (window.screen.height-h)/2;
	if (winl < 0) winl = 0;
	if (wint < 0) wint = 0;
	var settings = 'height=' + h + ',';
	settings += 'width=' + w + ',';
	settings += 'top=' + wint + ',';
	settings += 'left=' + winl + ',';
	settings += features;
	var name = window.open(page,name,settings);
	name.window.focus();
}

// format currency function
function format_currency(num){
	num = num.toString().replace(/\$|\,/g,'');
	if(isNaN(num))
	num = '0';
	sign = (num == (num = Math.abs(num)));
	num = Math.floor(num*100+0.50000000001);
	cents = num%100;
	num = Math.floor(num/100).toString();
	if(cents<10)
	cents = '0' + cents;
	for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
	num = num.substring(0,num.length-(4*i+3))+','+
	num.substring(num.length-(4*i+3));
	return (((sign)?'':'-') + '$' + num + '.' + cents);
}

// format percent function
function format_percent(num){
	num = num.toString().replace(/\%|\,/g,'');
	if (isNaN(num)){ num = '0'; }
	num = Math.abs(num*100)/100;
	num = Math.round(num*100)/100;
	return num + '%';
}

// format clean number function
function format_clean_number(num) {
    return Number(String(num).replace('$','').replace('%','').replace(/\,/g,''));
}

// create success message html
function successMessage(form, coupon){
	var html = '<div id="PBthankyou">' +
			   '<h1>Thank You!</h1>' +
			   '<p>Your information has been sent to our service department.<br /> We appreciate your business and will be contacting you shortly!</p>' +
			   coupon +
			   '</div>';

	$(form).closest('.PBform_wrap').html(html);
}

// process form
function processForm(form, coupon){
	$(form).find('.PBloading').show();
	$.ajax({
		type: 'POST',
		url: $(form).attr('action'),
		data: 'method=ajax&action=process_form&' + $(form).serialize(),
		success: function(){
			successMessage(form, coupon);
		}
	});
}

$(document).ready(function(){
	
	// currency
	if ($('input.currency').length) {
		$('input.currency').each(function(){
			$(this).val(format_currency($(this).val()));
		}).live('click', function(){
			if ($(this).val() == '$0.00') {
				$(this).val('');
			}
		}).live('blur', function(){
			$(this).val(format_currency($(this).val()));
		});	
	}
	
	// masked phone inputs
	if ($('.phone').length) {
		$('.phone').mask('(999) 999-9999');
	}
	
	// date picker default
	if ($('.datepicker').length) {
		$('.datepicker').datepicker();
	}
	
	// date picker month year
	if ($('.datepicker_my').length) {
		$('.datepicker_my').datepicker({
			changeMonth: true,
			changeYear: true
		});
	}
	
	// date picker month year with year range for date of birth
	if ($('.datepicker_dob').length) {
		var currentYear = (new Date).getFullYear();
		$('.datepicker_dob').datepicker({
			changeMonth: true,
			changeYear: true,
			yearRange: '1900:' + currentYear
		});
	}
	
	// submit form
	$('.PBsubmit_btn').click(function(){
		$(this).closest('form').validate({
			errorPlacement: function(error, element){},
			submitHandler: function(form){
				
				// check if it is a coupon form
				var coupon = '';
				if (form.id == 'coupon_form') {
					coupon = '<p><a href="javascript:void(0);" onclick="newWindow(\'' + $('input[name=coupon_details]').val() + '\',\'COUPONWINDOW\',\'800\',\'600\',\'\');">Click Here To Print Coupon</a></p>';
				}
				
				// check if they have recaptcha enabled
				if ($('#recaptcha_response_field').length) {
					var challenge_field = $('#recaptcha_challenge_field').val();
					var response_field = $('#recaptcha_response_field').val();
					$.post($(form).attr('action'), {
						method: 'ajax',
						action: 'recaptcha_check_answer',
						recaptcha_challenge_field: challenge_field,
						recaptcha_response_field: response_field
					}, function(data){
						// check if the recaptcha answer is valid
						if (typeof(data.is_valid_recaptcha) !== 'undefined' && data.is_valid_recaptcha === true) {
							processForm(form, coupon);
						} else {
							$('#recaptcha_response_field').addClass('error');
							alert('Your captcha is incorrect. Please try again.');
							Recaptcha.reload();
							return false;
						}
					}, 'text json');
				} else {
					processForm(form, coupon);
				}
			}
		});
	});
	
	// employment form
	if ($('#employment_form').length) {
		
		// show/hide fields
		$('#ever_employed_by_us_yes').click(function(){					   
			$('.ever_employed_by_us_yes').show();
		});
		$('#ever_employed_by_us_no').click(function(){					   
			$('.ever_employed_by_us_yes').hide();
		});
		
		$('#currently_employed_yes').click(function(){					   
			$('.currently_employed_yes').show();
			$('.currently_employed_no').hide();
		});
		$('#currently_employed_no').click(function(){					   
			$('.currently_employed_yes').hide();
			$('.currently_employed_no').show();
		});
		
		$('#bonded_yes').click(function(){					   
			$('.bonded_yes').show();
		});
		$('#bonded_no').click(function(){					   
			$('.bonded_yes').hide();
		});
		
		$('#felony_yes').click(function(){					   
			$('.felony_yes').show();
		});
		$('#felony_no').click(function(){					   
			$('.felony_yes').hide();
		});
		
	}
	
	// financing form
	if ($('#financing_form').length) {
		
		// show/hide fields
		if ($('#credit_applied_for_individual').is(':checked')) {
			$('.co_applicant_wrap').hide();
		} else {
			$('.co_applicant_wrap').show();
		}
		
		$('#credit_applied_for_joint').click(function(){					   
			$('.co_applicant_wrap').show();
		});
		
		$('#credit_applied_for_individual').click(function(){					   
			$('.co_applicant_wrap').hide();
		});
		
		// if no co-applicant remove required fields so it submits
		$('#financing_form').submit(function(){
			if ($('#credit_applied_for_individual').is(':checked')) {
				$('.co_applicant_wrap input.email').removeClass('required');
			} else {
				$('.co_applicant_wrap input.email').addClass('required');
			}
		  	return false;
		});
		
	}
	
});
