$(document).ready(function(){
var mortgage_check = 0;

  $("#loan_type, #credit_rating, #military_status, #va_before, #term_loan, #va_disabled, #home_value, #down_payment, #taxes, #insurance").change(function(){
    var loan_type = $('#loan_type').val();
    var home_amount = $('#home_value').val();
    var mil_exp = $('#military_status').val();
    var va_used = $('#va_before').val();
    var credit_est = $('#credit_rating').val();
    var down_payment = $('#down_payment').val();
    var loan_term = $('#term_loan').val();
    var va_disabled = $('#va_disabled').val();
    var taxes = $('#taxes').val();
    var insurance = $('#insurance').val();
    var rate = $('#current_rate').val();
    
    var url = 'http://www.valoancalculator.com/includes/formcalc.php?loan_type='+loan_type+'&home_amount='+home_amount+'&mil_exp='+mil_exp+'&va_used='+va_used+'&credit_est='+credit_est+'&down_payment='+down_payment+'&loan_term='+loan_term+'&va_disabled='+va_disabled+'&taxes='+taxes+'&insurance='+insurance+'&rate='+rate;
    $.get(url, "", function(data, status, xhr) {
      var values = eval('(' + data + ')');
      //$('#amount_down').html(down_payment);
      //$('.5down').html('$' + values.down_5);
      //$('.10down').html('$' + values.down_10);
      //$('#funding5').html('$' + values.funding_5);
      //$('#funding10').html('$' + values.funding_10);
      //$('#rate5').html(values.rate_percent_5 + '%');
      //$('#rate10').html(values.rate_percent_10 + '%');
      
      $('#est_funding_fee_container').html('$' + values.funding_fee);
      $('#va_funding_fee_container').html('$' + values.funding_fee);
      $('#amount_financed_container').html('$' + values.amount_financed);
      $('#estimated_taxes_container').html('$' + values.tax_insurance);
      $('#household_income_container').html('$' + values.household_income);
      $('#est_monthly_payment_container').html('$' + values.monthly_payment);
      
      $("#current_rate").val(values.new_rate1);
      if (values.rate != values.new_rate0 || values.rate != values.new_rate1 || values.rate != values.new_rate2) {
        //$('#current_rate').html('<option value="'+(parseFloat(values.new_rate1)-.25)+'">'+(parseFloat(values.new_rate1)-.25)+'%</option><option value="'+values.new_rate1+'" selected="selected">'+values.new_rate1+'%</option><option value="'+(parseFloat(values.new_rate1)+.25)+'">'+(parseFloat(values.new_rate1)+.25)+'%</option>');
      } else {
        //$('#current_rate').html('<option value="'+(parseFloat(values.rate)-.25)+'">'+(parseFloat(values.rate)-.25)+'%</option><option value="'+values.rate+'">'+values.rate+'%</option><option value="'+(parseFloat(values.rate)+.25)+'">'+(parseFloat(values.rate)+.25)+'%</option>');
      }
    });
    if (va_disabled == 'yes') {
      $('#not_disabled').hide();
      $('#disabled').show();
    } else {
      $('#not_disabled').show();
      $('#disabled').hide();
    }
  
  });

  $("#current_rate").change(function(){
    var loan_type = $('#loan_type').val();
    var home_amount = $('#home_value').val();
    var mil_exp = $('#military_status').val();
    var va_used = $('#va_before').val();
    var credit_est = $('#credit_rating').val();
    var down_payment = $('#down_payment').val();
    var loan_term = $('#term_loan').val();
    var va_disabled = $('#va_disabled').val();
    var taxes = $('#taxes').val();
    var insurance = $('#insurance').val();
    var rate = $('#current_rate').val();
    
    var url = 'http://www.valoancalculator.com/includes/formcalc.php?new_rate=no&loan_type='+loan_type+'&home_amount='+home_amount+'&mil_exp='+mil_exp+'&va_used='+va_used+'&credit_est='+credit_est+'&down_payment='+down_payment+'&loan_term='+loan_term+'&va_disabled='+va_disabled+'&taxes='+taxes+'&insurance='+insurance+'&rate='+rate;
    $.get(url, "", function(data, status, xhr) {
      var values = eval('(' + data + ')');
      $('#amount_down').html(down_payment);
      $('.5down').html('$' + values.down_5);
      $('.10down').html('$' + values.down_10);
      $('#funding5').html('$' + values.funding_5);
      $('#funding10').html('$' + values.funding_10);
      $('#rate5').html(values.rate_percent_5 + '%');
      $('#rate10').html(values.rate_percent_10 + '%');
      
      $('#est_funding_fee_container').html('$' + values.funding_fee);
      $('#va_funding_fee_container').html('$' + values.funding_fee);
      $('#amount_financed_container').html('$' + values.amount_financed);
      $('#estimated_taxes_container').html('$' + values.tax_insurance);
      $('#household_income_container').html('$' + values.household_income);
      $('#est_monthly_payment_container').html('$' + values.monthly_payment);
      
      if ($('#current_rate').val() == parseFloat(values.rate)-.25) var rate0_select = 'selected="selected" ';
      else var rate0_select = '';
      if ($('#current_rate').val() == parseFloat(values.rate)) var rate1_select = 'selected="selected" ';
      else var rate1_select = '';
      if ($('#current_rate').val() == parseFloat(values.rate)+.25) var rate2_select = 'selected="selected" ';
      else var rate2_select = '';
      
      //$('#current_rate').html('<option '+rate0_select+ 'value="'+(parseFloat(values.rate)-.25)+'">'+(parseFloat(values.rate)-.25)+'%</option><option '+rate1_select+ 'value="'+values.rate+'">'+values.rate+'%</option><option '+rate2_select+ 'value="'+(parseFloat(values.rate)+.25)+'">'+(parseFloat(values.rate)+.25)+'%</option>');
      
    if (va_disabled == 'yes') {
      $('#not_disabled').hide();
      $('#disabled').show();
    } else {
      $('#not_disabled').show();
      $('#disabled').hide();
    }
      
    });
  
  
  });

	$("#loan_type").change(function() {
		if ($('#loan_type').val() == "purchase") {
			$('.refi').hide();
			$('.result_note_black').show();
			$('.purch').show();
			mortgage_check = 0;
		} else {
			$('.purch').hide();
			$('.result_note_black').hide();
			$('.refi').show();
			mortgage_check = 1;
		}
	});  
  
	// Submit form to Vamclo
	$("#send_form_button").bind("mousedown", function() {
		validate(form_css);
	});

	$(form_css + " input, " + form_css + " textarea" + form_css + " select").bind("change", function() {
		sValidate($(this));
	});	

	function validate(id) {
		var submitable = true;
		//if (submitable != false){
			$(id + " input, " + id + " textarea" + form_css + " select").each(function() {
				submitable &= sValidate($(this));
			});
		//}
		if(!submitable) {
			//errors
			document.getElementById('error_box').style.display = 'block';
		}
		else {
			document.getElementById('error_box').style.display = 'none';
			$.ajax({
				type: "POST",
				url: "https://www.valoancalculator.com/backend.php",
				data: $("#top_content form").serialize(),
				success: function(msg){	
				$("form .right_column #form_fields").fadeOut("slow", function(){
						$("form .right_column #form_success").fadeIn("slow");
				/* conversion code variables */
						var google_conversion_id = 1070923029;
						var google_conversion_language = "en_US";
						var google_conversion_format = "1";
						var google_conversion_color = "ffffff";
						var google_conversion_label = "default";
						var microsoft_adcenterconversion_domainid = 3077;
						var microsoft_adcenterconversion_cp = 5050;
						var cc_tagVersion = "1.0";
						var cc_accountID = "1452799630";
						var cc_marketID =  "0";
						var cc_protocol="http";
						var cc_subdomain = "convctr";
						if(location.protocol == "https:")
						{
							cc_protocol="https";
							cc_subdomain="convctrs";
						}

						var cc_queryStr = "?" + "ver=" + cc_tagVersion + "&aID=" + cc_accountID + "&mkt=" + cc_marketID +"&ref=" + escape(document.referrer);
						var cc_imageUrl = cc_protocol + "://" + cc_subdomain + ".overture.com/images/cc/cc.gif" + cc_queryStr;
						var cc_imageObject = new Image();
						cc_imageObject.src = cc_imageUrl;
						$("#google_conversion").html('<noscript><img src="https://www.googleadservices.com/pagead/conversion/1070923029/?label=default&amp;script=0" style="display: none; height: 0;"></noscript><noscript><IMG SRC="http://3077.r.msn.com/?type=1&cp=1" style="display: none; height: 0;"/></noscript><a href="http://advertising.msn.com/MSNadCenter/LearningCenter/adtracker.asp" target="_blank" style="display: none; height: 0;">::adCenter::</a>');
						window.ysm_customData = new Object();
						window.ysm_customData.conversion = "transId=,currency=,amount=";
						var ysm_accountid  = "17ANPEKPN1S96QOLL02RVNS16M4";
						$.getScript("https://srv2.wa.marketingsolutions.yahoo.com/script/ScriptServlet?aid=" + ysm_accountid,function(){
							$.delay(600).getScript("https://0.r.msn.com/scripts/microsoft_adcenterconversion.js");
						});
						$.getScript("https://www.vamortgagecenter.com/js/prequalifyconfirm.js");
				});
			}
			});
		}
		return submitable;
	}	

	function sValidate(field) {
		valid = true;
		if(!field.hasClass('nocheck')) { 
			if(field.hasClass('required')) {
				if(jQuery.trim(field.val()) == '' || jQuery.trim(field.val()) == 'First' || jQuery.trim(field.val()) == 'Last') {
				  valid = false;
				}
			}	
			if (!field.is('select')) {
				var property_state = $('#property_state').val();
					if (property_state == '') {
						$('.state_label').css({"color":"#D00", "fontWeight":"bold", "fontSize":"90%"});
						valid = false;
					}else{
						$('.state_label').css({"color":"black", "fontWeight":"normal", "fontSize":"100%"});
					}
			}

      if (field.hasClass('terms_check')) {
        if (field.attr('checked') == false) {
          valid = false;
        } else {
          $('.terms_label').css({"color":"black", "fontWeight":"normal"});
        }
      }      
      
			if (mortgage_check && mortgage_check == 1) {
			if (!field.is('select')) {
				var mortgage_balance = $('#mortgage_balance').val();
				if (mortgage_balance == '') {
					$('.mortgage_label').css({"color":"#D00", "fontWeight":"bold", "fontSize":"90%"});
					valid = false;
				}else{
					$('.mortgage_label').css({"color":"black", "fontWeight":"normal", "fontSize":"100%"});
				}
			}
			}
			/*if(field.hasClass('state')) {
			var state = $('.state').val();
			alert(state);			  
				valid = false;			  
			}*/
			/*if(field.hasClass('phone_input3')){
			  if(jQuery.trim(field.length) != 3){
				valid = false;
			  }
			}*/
			/*if(field.hasClass('numeric')){
				if(!field.val().match(/[0-9]/)){
					valid = false;
				}
			}*/			

			if(field.hasClass('email')) {
			  if(!field.val().match(/^[a-z0-9!#$%&'*+\/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+\/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+(?:[a-z]{2,4}|museum|travel)$/i)) {
				valid = false;
			  }
			}
			var parent = field.closest(".field");
			var plabel = field.closest("label");
			if(!valid) {
				parent.addClass('field_fail');
				plabel.addClass('field_fail');
			}
			else {
				parent.removeClass("field_fail");
				plabel.removeClass("field_fail");
			}
			return valid;
		}
	}      
});
