$(document).ready(function() {
  if ( $('#car_years').length > 0 ) {
	car_year_init();
	car_make_init();
	car_model_init();
  }
  if ( $('.country_div').length > 0 ) {
	rate_country_init();
	rate_npa_init();
	// rate_nxx_init();
  }
});

function car_build_params() {
	var params = {};

	year = $('#car_years').val();
	if (year != '--') params.year = year;

	make = $('#car_makes').val();
	if (make != '--') params.make = make;

	model = $('#car_models').val();
	if (model != '--') params.model = model;

	return params;
}

function car_year_init() {
	$('#car_years').change(car_year_changed);
}

function car_year_changed() {
	$.get('/users/car_make_select_box', car_build_params(), function (data) {
		$('#car_makes').replaceWith(data);
		car_make_init();
	});

	car_make_changed();
}

function car_make_init() {
	$('#car_makes').change(car_make_changed);
}

function car_make_changed() {
	$.get('/users/car_model_select_box', car_build_params(), function (data) {
		$('#car_models').replaceWith(data);
		car_model_init();
	});
	car_model_changed();
}

function car_model_init() {
	$('#car_models').change(car_model_changed);
}

function car_model_changed() {
	$.get('/users/car_hidden_field', car_build_params(), function (data) {
		$('#user_car_id').replaceWith(data);
	});
}

function rate_build_params() {
  var params = {};

  params.id = $('#user_id').val();

  country_code = $('.country_div select').val();
  if (country_code != '') params.country_code = country_code;

  if ($('.npa_div').length > 0) {
	npa = $('.npa_div select').val();
	if (npa != '') params.npa = npa;
  }

  // if ($('.nxx_div').length > 0) {
  // 	nxx = $('.nxx_div select').val();
  // 	if (nxx != '--') params.nxx = nxx;
  // }

  return params;
}

function rate_country_init() {
  $('.country_div select').change(rate_country_changed);
}

function rate_country_changed() {
  $.get('/users/rate_npa_select_box', rate_build_params(), function (data) {
	$('.value_div').remove();
	// $('.nxx_div').remove();
	$('.npa_div').remove();
	$('.country_div').after(data);
	rate_npa_init();
  });
}

function rate_npa_init() {
  $('.npa_div select').change(rate_npa_changed);
}

// function rate_npa_changed() {
//   $.get('/users/rate_nxx_select_box', rate_build_params(), function (data) {
// 	$('.value_div').remove();
// 	$('.nxx_div').remove();
// 	$('.npa_div').after(data);
// 	rate_nxx_init();
//   });
// }

function rate_npa_changed() {
  $.get('/users/rate_value', rate_build_params(), function(data) {
	$('.value_div').remove();
	$('.npa_div').after(data);
  });
}

// function rate_nxx_init() {
//   $('.nxx_div select').change(rate_nxx_changed);
// }

// function rate_nxx_changed() {
//   $.get('/users/rate_value', rate_build_params(), function(data) {
// 	$('.value_div').remove();
// 	$('.nxx_div').after(data);
//   });
// }
