(function($) {
    "use strict";
	/**
	 * This function only used widget search filter box
	 */
    var jws_ajax_url = jws_script.ajax_url;
    var cars_price_slider_params_main = cars_price_slider_params;
    var cars_year_range_slider_params_main = cars_year_range_slider_params;
    var Cookies_main= Cookies;
    if(typeof goole_captcha_api_obj !== "undefined") {
        var goole_captcha_api_obj_main = goole_captcha_api_obj;
    }

	function do_cfb_ajax_call(form_data, col_class, selected_attr, sel_obj, current_selected_attr, uid, current_data_field) {
		$.ajax({
			url: jws_ajax_url,
			type: 'post',
			dataType: 'json',
			data: 'action=jws_cars_filter_query' + form_data + '&cfb=yes&box_type=' + col_class + '&selected_attr=' + selected_attr + '&query_nonce=' + cars_price_slider_params_main.jws_cars_filter_query_nonce + '&field_current=' + current_data_field,
			beforeSend: function() {
				$('.jws-cars-search').find('b').addClass('car-loader');
				$('.jws-cars-search').addClass('form-loader');
				$('.custom-filters-box').prop('disabled', true);
				$('.cfb-submit-btn').prop('disabled', true);
			},
			success: function(response) {
				if(response.status == "success") {
					if(typeof response.all_filters == "object") {
						$.each(response.all_filters, function(key, value) {
							var tax_label = $('#sort_' + key).attr('data-tax');
							var new_options = "<option value=''>" + tax_label + "</option>";
							if(typeof value == "object") {
								$.each(value, function(value_key, value_value) {
									$.each(value_value, function(new_value_key, new_value_value) {
										var selected_val = '';
										$.each(sel_obj, function(sel_obj_key) {
											if(sel_obj_key == key) {
												selected_val = "selected='selected'";
											}
										});
										if(key != "car_mileage") {
											new_options += "<option value='" + new_value_key + "' " + selected_val + ">" + new_value_value + "</option>";
										}
									});
								});
							}
							if(key != "car_mileage" && key != current_selected_attr) {
								$('#sort_' + key).html(new_options);
							}
						});
					}
					$('.jws-cars-search').removeClass('form-loader');
					$('.jws-cars-search').find('b').removeClass('car-loader');
					$('.custom-filters-box').prop('disabled', false);
					$('.cfb-submit-btn').prop('disabled', false);
					// Lazyload
					if($('section.lazyload').length > 0) {
						if(typeof response.tot_result != 'undefined' && response.tot_result < 1) {
							$('.all-cars-list-arch').attr('data-records', 0);
						} else {
							$('.all-cars-list-arch').removeAttr('data-records');
						}
					}
				}
			},
			error: function() {
				alert('Something went wrong!');
				$('.jws-cars-search').find('b').removeClass('car-loader');
				$('.jws-cars-search').removeClass('form-loader');
			}
		});
	}
	/*
	 * Get data using ajax method
	 */
	function do_ajax_call(form_data) {
		var is_author = '',
			author_id = '',
			is_user = '';
		if(cars_price_slider_params_main.cars_is_author == 'yes') {
			is_author = 'yes';
			author_id = cars_price_slider_params_main.author_id;
		}
		if(cars_price_slider_params_main.cars_is_user == 'yes') {
			is_user = 'yes';
		}
        $('html,body').animate({
			scrollTop: $(".all-cars-list-arch").offset().top - 80
		}, 600);
		$.ajax({
			url: jws_ajax_url,
			type: 'post',
			dataType: 'json',
			data: 'action=jws_cars_filter_query' + form_data + '&query_nonce=' + cars_price_slider_params_main.jws_cars_filter_query_nonce + '&is_author=' + is_author + '&author_id=' + author_id + '&is_user=' + is_user + '',
			beforeSend: function() {
				$('.sort-filters').addClass('form-loader');
				$('.select-sort-filters').prop('disabled', true);
				$('#submit_all_filters').prop('disabled', true);
				$('.all-cars-list-arch').addClass('loading');
			},
			success: function(response) {
				$('.all-cars-list-arch').removeClass('loading');
				$('.all-cars-list-arch').html(response.data_html);
				$('.jws-pagination-number').html(response.pagination_html);
				$('.cars-order').html(response.order_html);
				set_result_filters(response);
				$('.select-sort-filters').prop('disabled', false);
				$('#submit_all_filters').prop('disabled', false);
				$('.sort-filters').removeClass('form-loader');
				$('.pagination-loader').html('');
				$('.number_of_listings').html(response.tot_result);

				$('select').select2({
					dropdownAutoWidth: true
				});
				var get_first_charecter = form_data.charAt(0);
				if(get_first_charecter == '&') {
					form_data = form_data.replace('&', '?');
				}
				window.history.pushState(null, null, cars_price_slider_params_main.cars_form_url + form_data);
				if($('.cars-top-filters-box').length) {
					$("html, body").animate({
						scrollTop: $('.cars-top-filters-box').offset().top
					}, 200);
				}
				$(document.body).trigger("sticky_kit:recalc"); //doens't recalc
			},
			error: function() {
				alert('Something went wrong!');
				$('.sort-filters').removeClass('form-loader');
				$('.pagination-loader').html('');
			}
		});
		return false;
	}

	function set_result_filters(response) {
		var sel_obj = {};
		$('.select-sort-filters').each(function() {
			var tid = $(this).attr('data-id');
			var sel_val = $(this).val();
			if(sel_val != "") {
				sel_obj[tid] = sel_val;
			}
		});
		if(typeof response.all_filters == "object") {
			$.each(response.all_filters, function(key, value) {
				var tax_label = $('#sort_' + key).attr('data-tax');
				var new_options = "<option value=''>" + tax_label + "</option>";
				if(typeof value == "object") {
					$.each(value, function(value_key, value_value) {
						$.each(value_value, function(new_value_key, new_value_value) {
							var selected_val = '';
							$.each(sel_obj, function(sel_obj_key) {
								if(sel_obj_key == key) {
									selected_val = "selected='selected'";
								}
							});
							if(key != "car_mileage") {
								new_options += "<option value='" + new_value_key + "' " + selected_val + ">" + new_value_value + "</option>";
							}
						});
					});
				}
				if(key != "car_mileage") {
					$('#sort_' + key).html(new_options);
				}
			});
		}
	}

	function get_cfb_ajax_parameter_with_cfb_type($this) {
		var parameters_arr = {};
		var selectedattr = [];
		var current_data_field = [];
		var selobj = {};
		var formdata = "";
		var uid = "";
		var tid = '';
		var currentselectedattr = $($this).attr('data-id');
		$('.custom-filters-box').each(function() {
			tid = $(this).attr('data-id');
			var sel_val = $(this).val();
			if(tid) {
				uid = $(this).attr('data-uid');
				selectedattr.push(tid);
				if(sel_val != "") {
					formdata += "&" + tid + "=" + sel_val;
					current_data_field.push(tid);
					selobj[tid] = sel_val;
				}
			}
		});
		var col_class = '4';
		var box_type = $($this).hasClass('col-6');
		if(box_type) {
			col_class = '6';
		}
		if(document.getElementById('pgs_year_range_min')) {
			var pgs_year_range_min = $('#pgs_year_range_min').val();
			var pgs_year_range_max = $('#pgs_year_range_max').val();
			var default_year_min_val = $('#pgs_year_range_min').attr('data-yearmin');
			var default_year_max_val = $('#pgs_year_range_max').attr('data-yearmax');
			if(default_year_min_val != pgs_year_range_min || pgs_year_range_max != default_year_max_val) {
				formdata += "&min_year=" + pgs_year_range_min;
				formdata += "&max_year=" + pgs_year_range_max;
			}
		}
		formdata += "&current_attr=" + currentselectedattr;
		parameters_arr.selected_attr = selectedattr;
		parameters_arr.sel_obj = selobj;
		parameters_arr.form_data = formdata;
		parameters_arr.current_data_field = current_data_field;
		parameters_arr.uid = uid;
		parameters_arr.tid = tid;
		parameters_arr.col_class = col_class;
		parameters_arr.current_selected_attr = currentselectedattr;
		return parameters_arr;
	}

	function dealer_price_filter() {
		if(typeof cars_price_slider_params_main === 'undefined') {
			return false;
		}
		// Price slider uses $ ui
		var pgs_min_price = $('#pgs_min_price').data('min'),
			pgs_max_price = $('#pgs_max_price').data('max'),
			pgs_current_min_price = parseInt(pgs_min_price, 10),
			pgs_current_max_price = parseInt(pgs_max_price, 10);
		if(cars_price_slider_params_main.min_price) {
			pgs_current_min_price = parseInt(cars_price_slider_params_main.min_price, 10);
		}
		if(cars_price_slider_params_main.max_price) {
			pgs_current_max_price = parseInt(cars_price_slider_params_main.max_price, 10);
		}
		$(document.body).bind('pgs_price_slider_create pgs_price_slider_slide', function(event, min, max) {
			var currency_symbol = cars_price_slider_params_main.currency_symbol;
			switch(cars_price_slider_params_main.currency_pos) {
				case 'left':
					$('#dealer-slider-amount').val(currency_symbol + jws_addCommas(min) + " - " + currency_symbol + jws_addCommas(max));
					break;
				case 'left-with-space':
					$('#dealer-slider-amount').val(currency_symbol + ' ' + jws_addCommas(min) + " - " + currency_symbol + ' ' + jws_addCommas(max));
					break;
				case 'right-with-space':
					$('#dealer-slider-amount').val(jws_addCommas(min) + ' ' + currency_symbol + " - " + jws_addCommas(max) + ' ' + currency_symbol);
					break;
				default:
					$('#dealer-slider-amount').val(jws_addCommas(min) + currency_symbol + " - " + jws_addCommas(max) + currency_symbol);
			}
			$(document.body).trigger('price_slider_updated', [min, max]);
		});
		if($.isFunction($.fn.slider)) {
			var pgs_price_range_step = $('#pgs_max_price').data('step');
			var range_step = 100;
			if(pgs_price_range_step) {
				range_step = pgs_price_range_step;
			}
			$("#slider-range,#slider-range-2").slider({
				range: true,
				min: pgs_min_price,
				max: pgs_max_price,
				values: [pgs_current_min_price, pgs_current_max_price],
				step: range_step,
				create: function() {
					$('#pgs_min_price').val(pgs_current_min_price);
					$('#pgs_max_price').val(pgs_current_max_price);
					$(document.body).trigger('pgs_price_slider_create', [pgs_current_min_price, pgs_current_max_price]);
				},
				slide: function(event, ui) {
					var min = ui.values[0],
						max = ui.values[1];
					$('#pgs_min_price').val(min);
					$('#pgs_max_price').val(max);
					$(document.body).trigger('pgs_price_slider_slide', [ui.values[0], ui.values[1]]);
				},
				change: function(event, ui) {
					$(document.body).trigger('pgs_price_slider_change', [ui.values[0], ui.values[1]]);
				},
				stop: function() {
					var is_cfb = $(this).attr('data-cfb');
					if(is_cfb != 'yes') {
						var form_data = get_form_field(this);
						do_ajax_call(form_data);
					}
				}
			});
		}
	}

	function jws_addCommas(nStr) {
		return jws_number_format(nStr, parseInt(cars_price_slider_params_main.decimal_places), cars_price_slider_params_main.decimal_separator_symbol, cars_price_slider_params_main.thousand_seperator_symbol);
	}

	function jws_number_format(number, decimals, decPoint, thousandsSep) {
		decimals = decimals || 0;
		number = parseFloat(number);
		if(!decPoint || !thousandsSep) {
			decPoint = '.';
			thousandsSep = ',';
		}
		var roundedNumber = Math.round(Math.abs(number) * ('1e' + decimals)) + '';
		var numbersString = decimals ? roundedNumber.slice(0, decimals * -1) : roundedNumber;
		var decimalsString = decimals ? roundedNumber.slice(decimals * -1) : '';
		var formattedNumber = "";
		while(numbersString.length > 3) {
			formattedNumber += thousandsSep + numbersString.slice(-3);
			numbersString = numbersString.slice(0, -3);
		}
		return(number < 0 ? '-' : '') + numbersString + formattedNumber + (decimalsString ? (decPoint + decimalsString) : '');
	}

	function dealer_year_range_filter() {
		if(typeof cars_year_range_slider_params_main === 'undefined') {
			return false;
		}
		if(document.getElementById('slider-year-range')) {
			// Year range slider uses $ ui
			var pgs_year_range_min = $('#pgs_year_range_min').data('yearmin'),
				pgs_year_range_max = $('#pgs_year_range_max').data('yearmax'),
				pgs_current_min_year = parseFloat(pgs_year_range_min, 10),
				pgs_current_max_year = parseFloat(pgs_year_range_max, 10);
			if(cars_year_range_slider_params_main.min_year) {
				pgs_current_min_year = parseFloat(cars_year_range_slider_params_main.min_year, 10);
			}
			if(cars_year_range_slider_params_main.max_year) {
				pgs_current_max_year = parseFloat(cars_year_range_slider_params_main.max_year, 10);
			}
			$(document.body).bind('pgs_year_range_slider_create pgs_year_range_slider_slide', function(event, min, max) {
				//$('#dealer-slider-year-range').val( min + " - " + max);
				$('#dealer-slider-year-range').each(function() {
					$(this).val(min + " - " + max);
				});
				$(document.body).trigger('year_range_slider_updated', [min, max]);
			});
			if($.isFunction($.fn.slider)) {
				$(".slider-year-range").each(function() {
					$(this).slider({
						range: true,
						min: pgs_year_range_min,
						max: pgs_year_range_max,
						values: [pgs_current_min_year, pgs_current_max_year],
						create: function() {
							$('#pgs_year_range_min').val(pgs_current_min_year);
							$('#pgs_year_range_max').val(pgs_current_max_year);
							$(document.body).trigger('pgs_year_range_slider_create', [pgs_current_min_year, pgs_current_max_year]);
						},
						slide: function(event, ui) {
							var min = ui.values[0],
								max = ui.values[1];
							$('#pgs_year_range_min').val(min);
							$('#pgs_year_range_max').val(max);
							$(document.body).trigger('pgs_year_range_slider_slide', [ui.values[0], ui.values[1]]);
						},
						change: function(event, ui) {
							$(document.body).trigger('pgs_year_range_slider_change', [ui.values[0], ui.values[1]]);
						},
						stop: function() {
							var is_cfb = $(this).attr('data-cfb');
							if(is_cfb == 'yes') {
								var cfb_ajax_paramete = get_cfb_ajax_parameter_with_cfb_type(this);
								do_cfb_ajax_call(cfb_ajax_paramete.form_data, cfb_ajax_paramete.col_class, cfb_ajax_paramete.selected_attr, cfb_ajax_paramete.sel_obj, cfb_ajax_paramete[''], cfb_ajax_paramete.uid, cfb_ajax_paramete.current_data_field);
							} else {
								var form_data = get_form_field(this);
								do_ajax_call(form_data);
							}
						}
					});
				});
			}
		}
	}

	function get_cfb_form_field() {
		var form_data = '';
		$('.custom-filters-box').each(function() {
			var tid = $(this).attr('data-id');
			var sel_val = $(this).val();
			if(sel_val != "") {
				form_data += '<input type="text" name="' + tid + '" value="' + sel_val + '" />';
			}
		});
		var pgs_min_price = $('#pgs_min_price').val();
		var pgs_max_price = $('#pgs_max_price').val();
		form_data += '<input type="text" name="min_price" value="' + pgs_min_price + '" />';
		form_data += '<input type="text" name="max_price" value="' + pgs_max_price + '" />';
		if(document.getElementById('pgs_year_range_min')) {
			var pgs_year_range_min = $('#pgs_year_range_min').val();
			var pgs_year_range_max = $('#pgs_year_range_max').val();
			form_data += '<input type="text" name="min_year" value="' + pgs_year_range_min + '" />';
			form_data += '<input type="text" name="max_year" value="' + pgs_year_range_max + '" />';
		}
		$('<form>', {
			"id": "getCarsData",
			"html": form_data,
			"action": jws_obj.site_url+"/cars"
		}).appendTo(document.body).submit();
	}
	/*
	 * Create dynamically form fields for filtering
	 */
	function get_form_field($this) {
		var get_id = $($this).attr('id');
		var lay_style = "view-grid";
		var form_data = '';
		var form_data_ajax = '';
		var serch_filter = '';
		$('.select-sort-filters').each(function() {
			var tid = $(this).attr('data-id');
			var sel_val = $(this).val();
			$(this).removeClass('has_val');
			if(sel_val != "") {
				form_data += '<input type="text" name="' + tid + '" value="' + sel_val + '" />';
				form_data_ajax += "&" + tid + "=" + sel_val;
				serch_filter = '<span class="remove-cars-value" id="stripe-item-' + tid + '" data-type="' + tid + '" ><a href="javascript:void(0)"><i class="jws-icon-icon_close-1"></i></a></span>';
				$(this).parents('li').find('.clear-value').html(serch_filter);
				$(this).addClass('has_val');
			} else {
				$(this).parents('li').find('.clear-value .remove-cars-value').remove();
			}
		});
		var get_page_favorites = $('#get-page-favorites').val();
		if(get_page_favorites) {
			form_data += '<input type="text" name="page" value="' + get_page_favorites + '" />';
			form_data_ajax += "&page=" + get_page_favorites;
		}
		var pgs_cars_pp = $('#pgs_cars_pp').val();
		if(pgs_cars_pp) {
			form_data += '<input type="text" name="cars_pp" value="' + pgs_cars_pp + '" />';
			form_data_ajax += "&cars_pp=" + pgs_cars_pp;
		}
		var cars_orderby = $('#pgs_cars_orderby').val();
		if(cars_orderby) {
			form_data += '<input type="text" name="cars_orderby" value="' + cars_orderby + '" />';
			form_data_ajax += "&cars_orderby=" + cars_orderby;
		}
		var pgs_min_price = $('#pgs_min_price').val();
		var pgs_max_price = $('#pgs_max_price').val();
		var default_min_val = $('#pgs_min_price').attr('data-min');
		var default_max_val = $('#pgs_max_price').attr('data-max');
		if(default_min_val != pgs_min_price || pgs_max_price != default_max_val) {
			form_data += '<input type="text" name="min_price" value="' + pgs_min_price + '" />';
			form_data += '<input type="text" name="max_price" value="' + pgs_max_price + '" />';
			form_data_ajax += "&min_price=" + pgs_min_price;
			form_data_ajax += "&max_price=" + pgs_max_price;
		}
		//check is active year range slider
		if(cars_year_range_slider_params_main.is_year_range_active) {
			var serch_filter_min = '';
			var serch_filter_max = '';
			var pgs_year_range_min = $('#pgs_year_range_min').val();
			var pgs_year_range_max = $('#pgs_year_range_max').val();
			var default_year_min_val = $('#pgs_year_range_min').attr('data-yearmin');
			var default_year_max_val = $('#pgs_year_range_max').attr('data-yearmax');
			var tid_min = $('#pgs_year_range_min').attr('name');
			var tid_max = $('#pgs_year_range_max').attr('name');
			if(default_year_min_val != pgs_year_range_min || pgs_year_range_max != default_year_max_val) {
				form_data += '<input type="text" name="min_year" value="' + pgs_year_range_min + '" />';
				form_data += '<input type="text" name="max_year" value="' + pgs_year_range_max + '" />';
				form_data_ajax += "&min_year=" + pgs_year_range_min;
				form_data_ajax += "&max_year=" + pgs_year_range_max;
				serch_filter_min += '<span class="remove-cars-value" id="stripe-item-' + tid_min + '" data-type="' + tid_min + '" ><a href="javascript:void(0)"><i class="far fa-times-circle"></i></a></span>';
				serch_filter_max += '<span class="remove-cars-value" id="stripe-item-' + tid_max + '" data-type="' + tid_max + '" ><a href="javascript:void(0)"><i class="far fa-times-circle"></i></a></span>';
			}
			if(pgs_year_range_min != '') {
				$('.year-min-max .min').find('.clear-value').html(serch_filter_min);
			} else {
				$('.year-min-max .min').find('.clear-value').html('');
			}
			if(pgs_year_range_max != '') {
				$('.year-min-max .max').find('.clear-value').html(serch_filter_max);
			} else {
				$('.year-min-max .max').find('.clear-value').html('');
			}
		}
		var cars_order = '';
		if(get_id == "pgs_cars_order") {
			cars_order = $($this).attr('data-order');
			if(cars_order && cars_order != "" && cars_order != 'undefined') {
				form_data += '<input type="text" name="cars_order" value="' + cars_order + '" />';
				form_data_ajax += "&cars_order=" + cars_order;
			}
		} else {
			cars_order = $('#pgs_cars_order.active').attr('data-current_order');
			if(cars_order && cars_order != "" && cars_order != 'undefined') {
				form_data += '<input type="text" name="cars_order" value="' + cars_order + '" />';
				form_data_ajax += "&cars_order=" + cars_order;
			}
		}
		if($($this).hasClass('catlog-layout')) {
			lay_style = $($this + '.active').attr('data-id');
			if($($this).hasClass('view-grid')) {
				form_data += '<input type="text" name="cars_grid"  value="yes"/>';
			}
			if($($this).hasClass('view-list')) {
				form_data += '<input type="text" name="cars_grid"  value="no"/>';
			}
			form_data += '<input type="text" name="lay_style"  value="' + lay_style + '"/>';
			var cn_paged = null;
			$('.pagination-nav ul li span').each(function() {
				if($(this).hasClass('current')) {
					var cuernt_page = $(this).text();
					if(cuernt_page != null) {
						cn_paged = parseInt(cuernt_page);
					}
				}
			});
			form_data += '<input type="text" name="paged" value="' + cn_paged + '" />';
		} else {
			//if Cookies_main not set then get default option value
			if(jws_obj.lay_style != '') {
				lay_style = jws_obj.lay_style;
			}
			if($($this).hasClass('.change-layout')) {
				lay_style = $($this).attr('data-id');
			}
			var laystyle = Cookies_main.get('lay_style');
			if(laystyle != null) {
				lay_style = laystyle;
			}
			form_data += '<input type="text" name="lay_style"  value="' + lay_style + '"/>';
			form_data_ajax += "&lay_style=" + lay_style;
		}
		var pgs_cars_search = $('#pgs_cars_search').val();
		if(pgs_cars_search && pgs_cars_search != '' && pgs_cars_search != 'undefined') {
			form_data += '<input type="search" name="s" value="' + pgs_cars_search + '" />';
			form_data += '<input type="hidden" name="post_type" value="cars" />';
			form_data_ajax += "&s=" + pgs_cars_search;
			form_data_ajax += "&post_type=cars";
		}
		if(jws_obj.is_vehicle_cat) {
			/*form_data += '<input type="hidden" name="is_vehicle_cat" value="yes" />';*/
			form_data_ajax += "&is_vehicle_cat=yes";
			form_data_ajax += "&vehicle_cat=" + jws_obj.vehicle_cat;
		}
		if(jws_obj.vehicle_location) {
			form_data_ajax += "&vehicle_location=" + jws_obj.vehicle_location;
			form_data += '<input type="hidden" name="vehicle_location" value="' + jws_obj.vehicle_location + '" />';
		}
		if($($this).hasClass('catlog-layout')) {
			$('<form>', {
				"id": "getCarsData",
				"html": form_data,
				"action": cars_price_slider_params_main.cars_form_url
			}).appendTo(document.body).submit();
		} else {
			return form_data_ajax;
		}
	}
	$(document).ready(function($) {
		car_single_slider();
		/*
		 * This function use for custom filters sortcode
		 */
		$(document).on('change', '.custom-filters-box', function() {
			var cfb_ajax_paramete = get_cfb_ajax_parameter_with_cfb_type(this);
			do_cfb_ajax_call(cfb_ajax_paramete.form_data, cfb_ajax_paramete.col_class, cfb_ajax_paramete.selected_attr, cfb_ajax_paramete.sel_obj, cfb_ajax_paramete[''], cfb_ajax_paramete.uid, cfb_ajax_paramete.current_data_field);
		});
		$(document).on("click", ".cfb-submit-btn", function(e) {
			e.preventDefault();
			get_cfb_form_field(this);
		});
		var form_data = '';
		$(document).on('change', '.select-sort-filters', function() {
			var current_clicked_attr = $(this).attr('data-id');
			var current_clicked_value = $(this).val();
			var form_data = '';
			form_data += get_form_field(this);
			if(current_clicked_value != '') {
				var current_value = current_clicked_value;
				form_data += "&current_value=" + current_value;
				form_data += "&current_attr=" + current_clicked_attr;
			}
			do_ajax_call(form_data);
		});
		$(document).on('change', '#pgs_year_range_min,#pgs_year_range_max', function() {
			var form_data = '';
			form_data += get_form_field(this);
			do_ajax_call(form_data);
		});
		$('#pgs_cars_pp,#pgs_cars_orderby').on('change', function() {
			form_data = get_form_field(this);
			do_ajax_call(form_data);
		});
	});
	$(document).on('click', '#pgs_price_filter_btn,#pgs_cars_search_btn,#pgs_cars_order', function() {
		if($(this).hasClass('catlog-layout')) {
			var form_data = get_form_field(this);
		} else {
			var form_data = get_form_field(this);
			do_ajax_call(form_data);
		}
	});
	// remove a filter
	$(".clear-value").on("click", "span.remove-cars-value", function(e) {
		e.preventDefault();
		$(this).fadeOut(0, function() {
			$(this).remove();
			var data_type = $(this).attr('data-type');
			$('#sort_' + data_type).val('');
			$('.sort_' + data_type).val('');
			var form_data = get_form_field(this);
			do_ajax_call(form_data);
		});
	});
	$(document).on('click', '.jws-pagination-number.pagi-ajax ul li a', function() {
		var page_link = $(this).text();
		var prev = $(this).hasClass('prev');
		var next = $(this).hasClass('next');
		var form_data = get_form_field(this);
		$('html,body').animate({
			scrollTop: $("#primary").offset().top
		}, 600);
		$('.all-cars-list-arch').addClass('loading');
		$('.sort-filters').addClass('form-loader');
		if(prev) {
			$('.jws-pagination-number ul li span').each(function() {
				if($(this).hasClass('current')) {
					var cuernt_page = $(this).text();
					page_link = parseInt(cuernt_page) - 1;
				}
			});
		}
		if(next) {
			$('.jws-pagination-number ul li span').each(function() {
				if($(this).hasClass('current')) {
					var cuernt_page = $(this).text();
					page_link = parseInt(cuernt_page) + 1;
				}
			});
		}
		$.ajax({
			url: jws_ajax_url,
			type: 'post',
			dataType: 'json',
			data: 'action=jws_cars_filter_query&paged=' + page_link + form_data + '&query_nonce=' + cars_price_slider_params_main.jws_cars_filter_query_nonce,
			beforeSend: function() {
				$('.pagination-loader').html('<span class="pagination-loader"><i class="cd-loader"></i></span>');
				$('.select-sort-filters').prop('disabled', true);
				$('#submit_all_filters').prop('disabled', true);
			},
			success: function(response) {
				set_result_filters(response);
				$('.pagination-loader').html('');
				$('.all-cars-list-arch').removeClass('loading');
				$('.all-cars-list-arch').html(response.data_html);
				$('.jws-pagination-number').html(response.pagination_html);
				$('.cars-order').html(response.order_html);
				$('.select-sort-filters').prop('disabled', false);
				$('#submit_all_filters').prop('disabled', false);
				$('.sort-filters').removeClass('form-loader');

				//$('select').niceSelect('update');
				window.history.pushState(null, null, cars_price_slider_params_main.cars_form_url + '?paged=' + page_link + form_data);
				if($('.cars-top-filters-box').length) {
					$("html, body").animate({
						scrollTop: $('.cars-top-filters-box').offset().top
					}, 200);
				}
			},
			error: function() {
				alert('Something went wrong!');
				$('.pagination-loader').html('');
			}
		});
		return false;
	});
	dealer_price_filter();
	dealer_year_range_filter();
	$(document).on('click', '#reset_filters', function(event) {
		event.preventDefault();
		var form_data = '';
		var sort_by = jws_obj.default_sort_by; //default dropdown sort option
		$('.clear-value').empty();
		$('#pgs_cars_search').val('');
		$('#pgs_cars_pp').val($("#pgs_cars_pp option:first").val());
		$('#pgs_cars_orderby').val(sort_by);
        $('.select-sort-filters').each(function(){
			$(this).val('');
		});
		var pgs_min_price = $('#pgs_min_price').data('min'),
			pgs_max_price = $('#pgs_max_price').data('max'),
			pgs_current_min_price = parseInt(pgs_min_price, 10),
			pgs_current_max_price = parseInt(pgs_max_price, 10);
		var currency_symbol = cars_price_slider_params_main.currency_symbol;
		$('#pgs_min_price').val(pgs_min_price);
		$('#pgs_max_price').val(pgs_max_price);
		switch(cars_price_slider_params_main.currency_pos) {
			case 'left':
				$('#dealer-slider-amount').val(currency_symbol + jws_addCommas(pgs_current_min_price) + " - " + currency_symbol + jws_addCommas(pgs_current_max_price));
				break;
			case 'left-with-space':
				$('#dealer-slider-amount').val(currency_symbol + ' ' + jws_addCommas(pgs_current_min_price) + " - " + currency_symbol + jws_addCommas(pgs_current_max_price));
				break;
			case 'right-with-space':
				$('#dealer-slider-amount').val(jws_addCommas(pgs_current_min_price) + currency_symbol + " - " + jws_addCommas(pgs_current_max_price) + ' ' + currency_symbol);
				break;
			default:
				$('#dealer-slider-amount').val(jws_addCommas(pgs_current_min_price) + currency_symbol + " - " + jws_addCommas(pgs_current_max_price) + currency_symbol);
		}
		$(document.body).trigger('price_slider_updated', [pgs_current_min_price, pgs_current_max_price]);
		if(cars_year_range_slider_params_main.is_year_range_active) {
			// Year range slider uses $ ui
			var pgs_year_range_min = $('#pgs_year_range_min').data('yearmin'),
				pgs_year_range_max = $('#pgs_year_range_max').data('yearmax'),
				pgs_current_min_year = parseInt(pgs_year_range_min, 10),
				pgs_current_max_year = parseInt(pgs_year_range_max, 10);
			$('#pgs_year_range_min').val(pgs_year_range_min);
			$('#pgs_year_range_max').val(pgs_year_range_max);
			$('#dealer-slider-year-range').val(pgs_current_min_year + " - " + pgs_current_max_year);
			$(document.body).trigger('year_range_slider_updated', [pgs_current_min_year, pgs_current_max_year]);
		}
		form_data = get_form_field(this);
		do_ajax_call(form_data);
		dealer_price_filter();
		if(cars_year_range_slider_params_main.is_year_range_active) {
			dealer_year_range_filter();
		}
	});
	// compare
	$(document).on('click', '.car-compare', function(e) {
		var target = $(e.target).closest('[data-id]');
		var dataId = target.attr('data-id');
		if(target.hasClass('added')) return true;
		e.preventDefault();
		var dataAction = 'add';
		$.ajax({
			url: jws_ajax_url,
			type: "POST",
			dataType: 'json',
			data: '&post_id=' + dataId + '&post_action=' + dataAction + '&action=jws_ajax_add_to_compare',
			context: this,
			beforeSend: function() {
				target.addClass('loading');
			},
			success: function(data) {
				target.addClass('added');
				$('.single-add-to-compare').addClass('single-add-to-compare-visible');
				if(typeof data.response != 'undefined') {
					$('.single-add-to-compare .jws-title').text(data.response);
				}
				if(typeof data.length != 'undefined') {
					$('.jws-current-cars-in-compare').text(data.length);
				}
				setTimeout(function() {
					$('.single-add-to-compare').removeClass('single-add-to-compare-visible');
				}, 5000);
				if(data.status === 'danger') {
					return;
				}
			},
			complete: function() {
				target.removeClass('loading');
			}
		});
	});
	// Favorites
	function car_favorites() {
		$('body.logged-in .jws-car-favorite').on('click', function(e) {
			e.preventDefault();
			if($(this).hasClass('disabled')) {
				return false;
			}
			$(this).toggleClass('active');
			var jws_car_add_to = $(this).data('id');
			$.ajax({
				url: jws_ajax_url,
				type: "POST",
				dataType: 'json',
				data: '&car_id=' + jws_car_add_to + '&action=jws_ajax_add_to_favourites',
				context: this,
				beforeSend: function() {
					$(this).addClass('disabled');
				},
				success: function(data) {
					if(data.count) {
						$('.jws-my-favourites span').text(data.count);
					}
					$(this).removeClass('disabled');
				}
			});
		});
		$('body.user-not-logged-in .jws-car-favorite').on('click', function(e) {
			e.preventDefault();
			$(this).toggleClass('active');
			var jws_Cookies_main = Cookies_main();
			var jws_car_add_to = $(this).data('id');
			var jws_car_favourites = [];
			if(typeof(jws_Cookies_main.jws_car_favourites) !== 'undefined') {
				jws_car_favourites = jws_Cookies_main.jws_car_favourites.split(',');
				var index = jws_car_favourites.indexOf(jws_car_add_to.toString());
				if(index !== -1) {
					jws_car_favourites.splice(index, 1);
				} else {
					jws_car_favourites.push(jws_car_add_to.toString());
				}
				jws_car_favourites = jws_car_favourites.join(',');
				Cookies_main.set('jws_car_favourites', jws_car_favourites, {
					expires: 7,
					path: '/'
				});
			} else {
				Cookies_main.set('jws_car_favourites', jws_car_add_to.toString(), {
					expires: 7,
					path: '/'
				});
			}
		});
		var ids = Cookies_main.get('jws_car_favourites');
		if(ids) {
			ids = ids.split(',');
		} else {
			ids = [];
		}
		if($('body').hasClass('logged-in')) {
			$.getJSON(jws_ajax_url, {
				action: 'jws_ajax_get_favourites'
			}, function(data) {
				ids = data;
				activateLinks(ids);
			});
		} else {
			activateLinks(ids);
		}
	}
	car_favorites();

	function activateLinks(ids, ctx) {
		$.each(ids, function(key, value) {
			if(!value) {
				return;
			}
			$('.jws-car-favorite', ctx).filter('[data-id=' + value + ']').addClass('active').attr('title', 'remove from favorites');
		});
	}
	$('.view-list').on('click', function() {
		$('.view-grid').removeClass('sel-active');
		$('.view-list').addClass('sel-active');
		$("div.cars-loop").fadeOut(300, function() {
			$(this).addClass("cars-list").fadeIn(300);
		});
		Cookies_main.set('lay_style', 'view-list');
		var form_data = get_form_field(this);
		do_ajax_call(form_data);
	});
	$('.view-grid').on('click', function() {
		$('.view-list').removeClass('sel-active');
		$('.view-grid').addClass('sel-active');
		$("div.cars-loop").fadeOut(300, function() {
			$(this).removeClass("cars-list").fadeIn(300);
		});
		Cookies_main.set('lay_style', 'view-grid');
		var form_data = get_form_field(this);
		do_ajax_call(form_data);
	});
	$(document).on('click', '.car-gallery', function(e) {
		e.preventDefault();
        var galleryImages = '';
		if($(this).data('links') != undefined) {
			 galleryImages = $(this).data('links').split(',');
		}
		if(galleryImages.length > 0) {
			var srcset = [];
			for(var i = 0; i < galleryImages.length; i++) {
				srcset.push({
					'src': galleryImages[i],
					'thumb': galleryImages[i],
					'subHtml': '',
					'width': 640
				});
			}
			$(this).lightGallery({
				dynamic: true,
				dynamicEl: srcset
			});
		}
	});

	function car_single_slider() {
		if(typeof($.fn.lightGallery) == 'undefined') return;
		$('.single-inventory .images-slider').lightGallery({
			thumbnail: true,
			swipeToSlide: true,
		});
		$('.images-slider').on('swipe', function() {
			$('body').addClass('lg-on');
		}).on('afterChange', function() {
			$('body').removeClass('lg-on');
		});
        var $carousel = $('.single-inventory .images-slider');
		// Card's slider
		if($('.single-inventory').hasClass('layout1')) {
			$carousel.slick({
				slidesToShow: 1,
				slidesToScroll: 1,
				prevArrow: '<span class="jws-carousel-btn prev-item"><i class="jws-icon-arrow_carrot-left"></i></span>',
				nextArrow: '<span class="jws-carousel-btn next-item "><i class="jws-icon-arrow_carrot-right"></i></span>',
				adaptiveHeight: true,
				asNavFor: '.thumbnail-slider',
				swipeToSlide: true,
			});
			$('.thumbnail-slider').slick({
				slidesToShow: 4,
				slidesToScroll: 1,
				asNavFor: '.images-slider',
				dots: false,
				centerMode: false,
				focusOnSelect: true,
				arrows: false,
				swipeToSlide: true,
			});
		} else {
			$carousel.slick({
				prevArrow: '<span class="jws-carousel-btn prev-item"><i class="jws-icon-arrow_carrot-left"></i></span>',
				nextArrow: '<span class="jws-carousel-btn next-item "><i class="jws-icon-arrow_carrot-right"></i></span>',
				swipeToSlide: true,
			});
		}
		// $('.car-video-popup-wap').lightGallery();
		$(document).on('click', '.car-video-popup', function(e) {
			e.preventDefault();
            var videolist;
			if($(this).attr('href') != undefined) {
				videolist = $(this).attr('href').split(',');
			}
			if(videolist.length > 0) {
				var srcset = [];
				for(var i = 0; i < videolist.length; i++) {
					srcset.push({
						'src': videolist[i],
						'thumb': videolist[i],
						'subHtml': '',
						'width': 640
					});
				}
				$(this).lightGallery({
					dynamic: true,
					dynamicEl: srcset
				});
			}
		});
	}
	// car share
	$(document).on('click', '.car-share-btn', function() {
		var parents = $(this).parents('.car-share');
		parents.toggleClass('opened');
	});

	function do_validate_field(textArray, formId, SelectArray) {
		var validationStr = false;
        var n = 0;
        var field_val; 
		// code for privacy and terms
		if($('.validation_error').length) {
			$('.validation_error').css("border", "none");
		}
		if($('form#' + formId).find('input:checkbox[name=jws_terms_privacy]').length > 0) {
			var checkbox_field = $('form#' + formId).find('input:checkbox[name=jws_terms_privacy]:checked').val();
			$('form#' + formId).find('input:checkbox[name=jws_terms_privacy]').parent().parent('div').removeClass('validation_error');
			if(checkbox_field == null || checkbox_field == "") {
				validationStr = true;
				$('form#' + formId).find('input:checkbox[name=jws_terms_privacy]').parent().parent('div').addClass('validation_error');
			}
		}
		for(n = 0; n < textArray.length; n++) {
			var str = textArray[n];
			$('form#' + formId).find('input[name=' + str + ']').css({
				"border": "none"
			});
			field_val = $('form#' + formId).find('input[name=' + str + ']').val();
			if(field_val == "") {
				validationStr = true;
				$('form#' + formId).find('input[name=' + str + ']').css({
					"border-style": "solid",
					"border-width": "1px 1px 1px 1px",
					"border-color": "red"
				});
			}
			if($("input[name=" + str + "]").hasClass('jws_mail')) {
				var varTejwsailExp = /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
				var varEmail = field_val;
				if(varEmail && varEmail.search(varTejwsailExp) == -1) {
					validationStr = true;
					$('form#' + formId).find('input[name=' + str + ']').css({
						"border-style": "solid",
						"border-width": "1px 1px 1px 1px",
						"border-color": "red"
					});
				}
			}
		}
		if(typeof SelectArray != 'undefined') {
			if(SelectArray) {
			    
				for( n = 0; n < SelectArray.length; n++) {
					var str = SelectArray[n];
					$('form#' + formId).find('select[name=' + str + ']').next('.nice-select').css({
						"border-color": "#e3e3e3"
					});
					field_val = $('form#' + formId).find('select[name=' + str + ']').val();
					if(field_val == "") {
						validationStr = true;
						$('form#' + formId).find('select[name=' + str + ']').next('.nice-select').css({
							"border-style": "solid",
							"border-width": "1px 1px 1px 1px",
							"border-color": "red"
						});
					}
				}
			}
		}
		return validationStr;
	}

	function form_contact_ajax() {
		/***************************************
		:: Car contact Form [ CarDetail Page ]
		***************************************/
		$(document).on('click', '#submit_request', function(e) {
			e.preventDefault();
			var formId = $(this).parents("form").attr('id');
			var form_value = $(this).parents('form');
			$('form#' + formId).find('input').css({
				"border": "none"
			});
			var textArray = [];
			$('form#' + formId).find('input.jws_validate').each(function(i) {
				textArray[i] = $(this).attr('name');
			});

			// ENABLE / DISABLE REQUIRED ON PHONE / EMAIL BASED ON PREFERED CONTACT SELECTED
			var sts = do_validate_field(textArray, formId);
			if(!sts) {
				$.ajax({
					url: jws_ajax_url,
					method: "POST",
					dataType: 'json',
					data: form_value.serialize(),
					beforeSend: function() {
						$('#submit_request').addClass('form-loader');
						$(this).prop("disabled", "disabled");
					},
					success: function(responseObj) {
						$('form#' + formId + ' .contact-msg').show();
						$(this).removeAttr("disabled");
						$('.spinimg').html('');
						$('form#' + formId + ' .contact-msg').html(responseObj.msg).delay(5000).fadeOut('slow');
						if(responseObj.status == 1) $('form#' + formId).find("input[type=text], input[type=number], textarea, radio").val("");
						$('.check').attr('checked', true);
						if(typeof grecaptcha !== "undefined") {
							grecaptcha.reset();
						}
						$('#submit_request').removeClass('form-loader');
					}
				});
			}
		});
	}
	form_contact_ajax();

	function car_test_drive_form() {
		$('.show_test_drive').css('display', 'block');
		$(document).on('click', '#schedule_test_request', function(e) {
			e.preventDefault();
			var formId = $(this).parents('form').attr('id');
			var carId = $(this).parents('form').attr('id');
			var form_value = $(this).parents('form');
			$('form#' + formId).find('input').css({
				"border": "none"
			});
			var textArray = [];
			$('form#' + formId).find('input.jws_validate').each(function(i) {
				textArray[i] = $(this).attr('name');
			});
			var sts = do_validate_field(textArray, formId);
			if(!sts) {
				var submit_btn_ID = $(this).attr('id');
				carId = $(this).attr('car-id');
				$.ajax({
					url: jws_ajax_url,
					method: "POST",
					data: form_value.serialize(),
					dataType: 'json',
					beforeSend: function() {
						$('#schedule_test_request').addClass('form-loader');
						$('#' + submit_btn_ID).prop("disabled", "disabled");
					},
					success: function(responseObj) {
						$('form#schedule_test_form .schedule_test_msg').show();
						$('form#schedule_test_form .schedule_test_msg').html(responseObj.msg).delay(5000).fadeOut('slow');
						if(responseObj.status == 1) {
							$('form#schedule_test_form').find("input[type=text], input[type=number], textarea, radio").val("");
							$('.check').attr('checked', true);
						}
						if(typeof grecaptcha !== "undefined") {
							grecaptcha.reset();
						}
						$('#' + submit_btn_ID).removeAttr("disabled");
						$('#schedule_test_request').removeClass('form-loader');
					}
				});
			}
		});
	}
	car_test_drive_form();
	/***************************************
	:: Car quote Form
	***************************************/
	function form_quote_ajax() {
		$(document).on('click', '#submit_quouest', function(e) {
			e.preventDefault();
			var formId = $(this).parents("form").attr('id');
			var form_value = $(this).parents('form');
			$('form#' + formId).find('input').css({
				"border": "none"
			});
			var textArray = [];
			$('form#' + formId).find('input.jws_validate').each(function(i) {
				textArray[i] = $(this).attr('name');
			});
			// ENABLE / DISABLE REQUIRED ON PHONE / EMAIL BASED ON PREFERED CONTACT SELECTED
			var sts = do_validate_field(textArray, formId);
			if(!sts) {
				var submit_btn_ID = $(this).attr('id');
				$.ajax({
					url: jws_ajax_url,
					method: "POST",
					dataType: 'json',
					data: form_value.serialize(),
					beforeSend: function() {
						$('#submit_quouest').addClass('form-loader');
						$('#' + submit_btn_ID).prop("disabled", "disabled");
					},
					success: function(responseObj) {
						$('form#' + formId + ' .quote-msg').show();
						$('#' + submit_btn_ID).removeAttr("disabled");
						$('#submit_quouest').removeClass('form-loader');
						$('form#' + formId + ' .quote-msg').html(responseObj.msg).delay(5000).fadeOut('slow');
						if(responseObj.status == 1) $('form#' + formId).find("input[type=text], input[type=number], textarea, radio").val("");
						$('.check').attr('checked', true);
						if(typeof grecaptcha !== "undefined") {
							grecaptcha.reset();
						}
					}
				});
			}
		});
	}
	form_quote_ajax();
	/***************************************
	:: Car quote Form
	***************************************/
	function form_availability_ajax() {
		$(document).on('click', '#submit_avaiuest', function(e) {
			e.preventDefault();
			var formId = $(this).parents("form").attr('id');
			var form_value = $(this).parents('form');
			$('form#' + formId).find('input').css({
				"border": "none"
			});
			var textArray = [];
			$('form#' + formId).find('input.jws_validate').each(function(i) {
				textArray[i] = $(this).attr('name');
			});
			// ENABLE / DISABLE REQUIRED ON PHONE / EMAIL BASED ON PREFERED CONTACT SELECTED
			var sts = do_validate_field(textArray, formId);
			if(!sts) {
				var submit_btn_ID = $(this).attr('id');
				$.ajax({
					url: jws_ajax_url,
					method: "POST",
					dataType: 'json',
					data: form_value.serialize(),
					beforeSend: function() {
						$('#submit_avaiuest').addClass('form-loader');
						$('#' + submit_btn_ID).prop("disabled", "disabled");
					},
					success: function(responseObj) {
						$('form#' + formId + ' .avaite-msg').show();
						$('#' + submit_btn_ID).removeAttr("disabled");
						$('#submit_avaiuest').removeClass('form-loader');
						$('form#' + formId + ' .avaite-msg').html(responseObj.msg).delay(5000).fadeOut('slow');
						if(responseObj.status == 1) $('form#' + formId).find("input[type=text], input[type=number], textarea, radio").val("");
						$('.check').attr('checked', true);
						if(typeof grecaptcha !== "undefined") {
							grecaptcha.reset();
						}
					}
				});
			}
		});
	}
	form_availability_ajax();
	/*******************************************
		:: Make An Offer Form [ CarDetail Page ]
		*******************************************/
	function form_offer_ajax() {
		$(document).on('click', '#submit_offer', function(e) {
			e.preventDefault();
			var formId = $(this).parents('form').attr('id');
			var form_value = $(this).parents('form');
			var textArray = [];
			$('form#' + formId).find('input.jws_validate').each(function(i) {
				textArray[i] = $(this).attr('name');
			});
			var sts = do_validate_field(textArray, formId);
			if(!sts) {
				var submit_btn_ID = $(this).attr('id');
				$.ajax({
					url: jws_ajax_url,
					method: "POST",
					data: form_value.serialize(),
					dataType: 'json',
					beforeSend: function() {
						$('#submit_offer').addClass('form-loader');
						$('#' + submit_btn_ID).prop("disabled", "disabled");
					},
					success: function(responseObj) {
						$('form#make_an_offer_test_form .make_an_offer_test_msg').show();
						$('form#make_an_offer_test_form .make_an_offer_test_msg').html(responseObj.msg).delay(5000).fadeOut('slow');
						if(responseObj.status == 1) $('form#make_an_offer_test_form').find("input[type=text], textarea, radio").val("");
						$('.check').attr('checked', true);
						if(typeof grecaptcha !== "undefined") {
							grecaptcha.reset();
						}
						$('#' + submit_btn_ID).removeAttr("disabled");
						$('#submit_offer').removeClass('form-loader');
					}
				});
			}
		});
	}
	form_offer_ajax();

	function form_request_rent_ajax() {
		/***************************************
		:: Car contact Form [ CarDetail Page ]
		***************************************/
		$(document).on('click', '#rent_request', function(e) {
			e.preventDefault();
			var form = $(this).parents("#request-form").find('form');
			var formId = form.attr('id');
			var form_value = form;
			$('form#' + formId).find('input').css({
				"border": "none"
			});
			var textArray = [];
			$('form#' + formId).find('input.jws_validate').each(function(i) {
				textArray[i] = $(this).attr('name');
			});

			// ENABLE / DISABLE REQUIRED ON PHONE / EMAIL BASED ON PREFERED CONTACT SELECTED
			var sts = do_validate_field(textArray, formId);
			if(!sts) {
				var submit_btn_ID = $(this).attr('id');
				$.ajax({
					url: jws_ajax_url,
					method: "POST",
					dataType: 'json',
					data: form_value.serialize(),
					beforeSend: function() {
						$('#rent_request').addClass('form-loader');
						$('#' + submit_btn_ID).prop("disabled", "disabled");
					},
					success: function(responseObj) {
						console.log(responseObj);
						$('form#' + formId + ' .contact-msg').show();
						$('#' + submit_btn_ID).removeAttr("disabled");
						$('.spinimg').html('');
						$('form#' + formId + ' .contact-msg').html(responseObj.msg).delay(5000).fadeOut('slow');
						if(responseObj.status == 1) $('form#' + formId).find("input[type=text], input[type=number], textarea, radio").val("");
						$('.check').attr('checked', true);
						if(typeof grecaptcha !== "undefined") {
							grecaptcha.reset();
						}
						$('#rent_request').removeClass('form-loader');
					}
				});
			}
		});
	}
	form_request_rent_ajax();

	function get_car_contact_form() {
		// Open popup with product info when click on Quick View button

		$(document).on('click', '.open-modal', function(e) {
			e.preventDefault();
            var recaptcha1 , recaptcha2 , recaptcha3 , recaptcha4 , recaptcha5 , recaptcha6;
			check_filed_rent();
            get_value_form_rent_single();
			if(check_filed_rent()) {
				$('html, body').animate({
					scrollTop: $('.jws-adsearch-filter').offset().top - 150
				}, 100);
				return false;
			}
			if($(this).hasClass('content-loaded')) {
				open_model($(this));
				return false;
			}
			open_model($(this));
			var carId = $(this).data('car_id'),
				btn_type = $(this).data('type'),
				$this = $(this);
			var btn = $(this);
			btn.addClass('loading');
			var data = {
				type: btn_type,
				id: carId,
				action: "jws_ajax_load_car_form_contact",
			};
			$this.next('.car-form-popup').find('.car-form-popup-inner').append('<div class="car-form-popup-inner-animation"></div>');
			$.ajax({
				url: jws_ajax_url,
				data: data,
				method: 'get',
				success: function(data) {
					$this.next('.car-form-popup').find('.car-form-popup-inner-animation').addClass('has-content').append(data);
					btn.addClass('content-loaded');
					btn.removeClass('loading');
					get_value_form_rent_single();
					if(typeof goole_captcha_api_obj !== "undefined") {
						setTimeout(function() {
							//Render the recaptcha1 on the element with ID "recaptcha1"
							if(btn_type == 'contact') {
								 recaptcha1 = grecaptcha.render('recap1-' + carId + '', {
									'sitekey': goole_captcha_api_obj_main.google_captcha_site_key, //Replace this with your Site key
									'theme': 'light'
								});
							}
							if(btn_type == 'test') {
								 recaptcha2 = grecaptcha.render('recap2-' + carId + '', {
									'sitekey': goole_captcha_api_obj_main.google_captcha_site_key, //Replace this with your Site key
									'theme': 'light'
								});
							}
							if(btn_type == 'quote') {
								 recaptcha3 = grecaptcha.render('recap3-' + carId + '', {
									'sitekey': goole_captcha_api_obj_main.google_captcha_site_key, //Replace this with your Site key
									'theme': 'light'
								});
							}
							if(btn_type == 'offer') {
								 recaptcha4 = grecaptcha.render('recap4-' + carId + '', {
									'sitekey': goole_captcha_api_obj_main.google_captcha_site_key, //Replace this with your Site key
									'theme': 'light'
								});
							}
							if(btn_type == 'availability') {
								 recaptcha5 = grecaptcha.render('recap5-' + carId + '', {
									'sitekey': goole_captcha_api_obj_main.google_captcha_site_key, //Replace this with your Site key
									'theme': 'light'
								});
							}
							if(btn_type == 'request') {
								 recaptcha6 = grecaptcha.render('recap2-' + carId + '', {
									'sitekey': goole_captcha_api_obj_main.google_captcha_site_key, //Replace this with your Site key
									'theme': 'light'
								});
							}
						}, 500);
					}
				},
				complete: function() {},
				error: function() {},
			});
		});
	}
	get_car_contact_form();

	function get_value_form_rent_single() {
		$('.location-up p').text($('.formSearchUpLocation2').val());
		$('.location-end p').text($('.formSearchOffLocation2').val());
		$('.date-up p').text($('.jws-date-timepicker-start').val());
		$('.date-end p').text($('.jws-date-timepicker-end').val());
	}

	function check_filed_rent() {
		$('.drolocation,.jws-date-timepicker-start,.jws-date-timepicker-end').removeClass('jws_error');
		var jws_pickup_location = $('.formSearchUpLocation2').val();
		var jws_drop_location = $('.formSearchOffLocation2').val();
		var start_date = $('.jws-date-timepicker-start').val();
		var end_date = $('.jws-date-timepicker-end').val();
		var error = false;
		if(jws_pickup_location == 'none') {
			$('.formSearchUpLocation2').addClass('jws_error');
			error = true;
		}
		if(jws_drop_location == 'none') {
			$('.formSearchOffLocation2').addClass('jws_error');
			error = true;
		}
		if(start_date == '') {
			$('.jws-date-timepicker-start').addClass('jws_error');
			error = true;
		}
		if(end_date == '') {
			$('.jws-date-timepicker-end').addClass('jws_error');
			error = true;
		}
		return error;
	}

	function modal_popup() {
		$(document).on('click', '.close-modal , .modal-overlay , .cancel-form ', function(e) {
			e.preventDefault();
			close_model($(this));
		});
	}
	modal_popup();

	function open_model($taget) {
		var scrollWidth = window.innerWidth - $(document).width();
		var $modal_content = $taget.data('target');
		$($modal_content).addClass('opened');
		$($modal_content).fadeIn(300);
		$('html').addClass('model-open');
		$("html.model-open").css("margin-right", scrollWidth);
		$('.car-form-popup-inner-animation').addClass('has-content');
	}

	function close_model($taget) {
		var $modal_content = $taget.parents('.car-form-popup');
		$($modal_content).fadeOut(300);
		$($modal_content).removeClass('opened');
		$('html').removeClass('model-open');
		$('.car-form-popup-inner-animation').removeClass('has-content');
	}

	function car_single_tabs() {
		var $tabsdata = $(".tabs-nav li[data-tabs] , .write-review");
		$tabsdata.on('click', function() {
			var tabs_main = $(this).parents('.car-single-tabs,.calculate-tabs,.dealer-tabs');
			if($(this).hasClass('write-review')) {
				$('.tab3').click();
			}
			tabs_main.find('li[data-tabs]').removeClass('active');
			tabs_main.find('.tabcontent .cars-Tabs-panel').slideUp();
			var tab = $(this).data('tabs');
			$(this).addClass('active');
			$('#' + tab).find('.cars-Tabs-panel').slideDown();
			$('#' + tab).addClass('accordion-active');
			if(tab == 'tab4') {
				setTimeout(function() {
					tabs_main.find('.map_pin_jws').addClass('this');
				}, 320);
			} else {
				tabs_main.find('.map_pin_jws').removeClass('this');
			}
		});
		$(document).on('click', '.car-tabs .tab-heading', function() {
			$('.jws-group-accordion-wap').css("height", "auto");
			let tab_is_activated = $(this).closest('.accordion-active')[0];
			$('.car-tabs .accordion-active .cars-Tabs-panel').slideUp();
			$('.car-tabs .accordion-active').removeClass('accordion-active');
			var tab_id = $(this).parents('.tabcontent').attr('id');
			if(!tab_is_activated) {
				$(this).closest('.tabcontent').toggleClass('accordion-active');
				$(this).next('.cars-Tabs-panel').slideToggle();
				if($('.car-tabs .tabs-nav')[0]) {
					let id = $(this).parents('.tabcontent').attr('id');
					$('.car-tabs .tabs-nav .active').removeClass('active');
					$('.car-tabs .tabs-nav li[data-tabs="' + id + '"]').addClass('active');
				}
				if(tab_id == 'tab4') {
					setTimeout(function() {
						$('.map_pin_jws').addClass('this');
					}, 320);
				} else {
					$('.map_pin_jws').removeClass('this');
				}
			}
		});
		$(".tabcontent , .jws-group-accordion").on('click', '.accordion', function() {
			$(this).toggleClass('active');
			$(this).next('*').slideToggle();
		});
		$(".accordion").next('table').wrap('<div class="accordion_content"></div>');
	}
	car_single_tabs();
	/**************************************************
		  Financing Calculator
		**************************************************/
	function calculator_finance() {
		$(".stv-radio-tab").click(function() {
			var radioValue = $("input[name='apr']:checked").val();
			if(radioValue == '2') {
				$('.no-apr').hide();
				$('.my-apr').show();
				$("#score_credit").prop('disabled', true);
				$("#loan_term").prop('disabled', true);
			} else {
				$('.no-apr').show();
				$('.my-apr').hide();
				$("#score_credit").prop('disabled', false);
				$("#loan_term").prop('disabled', false);
			}
		});
		$(document).on('change', '#score_credit', function() {
			var score_value = $(this).val();
            var $m36,$m48,$m60,$m72;
			if(score_value == 'excellent') {
				$m36 = 1.99;
				$m48 = 2.49;
				$m60 = 2.99;
				$m72 = 3.24;
			}
			if(score_value == 'good') {
				$m36 = 3.49;
				$m48 = 3.74;
				$m60 = 3.99;
				$m72 = 4.24;
			}
			if(score_value == 'fair') {
				$m36 = 6.49;
				$m48 = 6.49;
				$m60 = 6.49;
				$m72 = 6.99;
			}
			if(score_value == 'rebuilding') {
				$m36 = 9.24;
				$m48 = 9.24;
				$m60 = 9.74;
				$m72 = 10.49;
			}
			var option_position = $('#loan_term').find(':selected').attr('data-position');
			document.getElementById("loan_term").innerHTML = '<option data-month="36" data-position="1" value="' + $m36 + '">36 mo ' + $m36 + '% APR</option><option data-month="48" data-position="2" value="' + $m48 + '">48 mo ' + $m48 + '% APR</option><option data-month="60" data-position="3" value="' + $m60 + '">60 mo ' + $m60 + '% APR</option><option data-month="72" data-position="4" value="' + $m72 + '">72 mo ' + $m72 + '% APR</option>';
			$("#loan_term option:nth-child(" + option_position + ")").attr("selected", "selected");
		});
		$(document).on('click', '.do_calculator', function() {
			calculator_finance_form();
		});
		$('.do_calculator_clear').click(function() {
			$('#sale_tax').val('0');
			$('#cash_down').val('0');
			$('#trade_value').val('0');
			$('#interest').val('0');
			$("#loan_term option").removeAttr("selected");
			$("#score_credit option").removeAttr("selected");
			$("#loan_term_2 option").removeAttr("selected");
			$("#loan_term option:nth-child(1)").attr("selected", "selected");
			$("#loan_term_2 option:nth-child(1)").attr("selected", "selected");
			$("#score_credit option:nth-child(1)").attr("selected", "selected");
			$("#score_credit").trigger("change");
			$(".do_calculator").trigger("click");
			$('#loan_term_2').trigger('change');
		});
	}
	calculator_finance();

	function calculator_finance_form() {
		if(typeof cars_price_slider_params_main === 'undefined') {
			return false;
		}
        var interest;
        var interest_rate;
        var period;
        var interest_rate_unused;
		var sale_tax = $('#sale_tax').val();
		var loan_amount = $('#price').val();
		var down_payment = $('#cash_down').val();
		var trade_value = $('#trade_value').val();
		if(!$('#loan_term').attr('disabled')) {
			interest = $("#loan_term").val();
			interest_rate = $("#loan_term").val() / 1200;
			period = $('#loan_term').find(':selected').attr('data-month');
		} else {
			interest = $("#interest").val();
			interest_rate = $("#interest").val() / 1200;
			period = $("#loan_term_2").val();
		}
		var currency_symbol = cars_price_slider_params_main.currency_symbol;
		interest_rate_unused = interest_rate;
		if(interest_rate == 0) {
			interest_rate_unused = 1;
		}
		interest_rate_unused = interest_rate;
		var mathPow = Math.pow(1 + interest_rate, period);
		if(interest_rate == 0) {
			interest_rate_unused = 1;
		}
		var monthly_payment = (interest_rate_unused != 1) ? (loan_amount - down_payment - trade_value) * interest_rate_unused * mathPow : (loan_amount - down_payment - trade_value) / period;
		var monthly_payment_div = (mathPow - 1);
		if(monthly_payment_div == 0) {
			monthly_payment_div = 1;
		}
		if(sale_tax > 0) {
			var sale_tax_payment = sale_tax * monthly_payment / 100;
			monthly_payment = sale_tax_payment + monthly_payment;
		}
		monthly_payment = monthly_payment / monthly_payment_div;
		monthly_payment = monthly_payment.toFixed(2);
		$(".month-price-results .price").html(currency_symbol + monthly_payment);
		$(".month-rt").html(period);
		$(".rate-rt").html(interest);
		$(".down-rt").html(currency_symbol + down_payment);
		$("#txtPayment .rate-results").html('for ' + period + ' months at ' + interest + '% APR ');
		$(".calculate-list-top .list-price").html('' + currency_symbol + loan_amount + '');
		$(".calculate-list-top .list-down").html('' + currency_symbol + down_payment + '');
		$(".calculate-list-top .list-trade").html('' + currency_symbol + trade_value + '');
		$(".calculate-list-top .list-sales").html('' + currency_symbol + sale_tax + '');
		var financed = monthly_payment * period;
		financed = financed.toFixed(2);
		$(".calculate-list-center .list-totals-financed").html('' + currency_symbol + financed + '');
		var totals_interest = monthly_payment * period - loan_amount;
		totals_interest = totals_interest.toFixed(2);
		$(".calculate-list-center .list-totals-interest").html('' + currency_symbol + totals_interest + '');
		var totals_loan = parseInt(totals_interest) + parseInt(financed);
		$(".calculate-list-bottom .list-totals-loan").html('' + currency_symbol + totals_loan + '');
	}

	function calculator_lease_form() {
		if(typeof cars_price_slider_params_main === 'undefined') {
			return false;
		}
		var loan_amount = $('#lease_price').val();
		var down_payment = $('#lease_cash_down').val();
		var lease_miles = $('#lease_miles').val();
		var lease_interest = $('#lease_interest').val();
		var lease_term = $('#lease_term').val();
		var lease_residual = $('#lease_residual').val();
		var price_final = loan_amount;
		var currency_symbol = cars_price_slider_params_main.currency_symbol;
		if(down_payment > 0) {
			price_final = loan_amount - down_payment;
		}
		$(document).on('change', '#lease_score_credit', function() {
			$('#lease_interest').val($(this).val());
		});
		var price_residual = 0;
		var lease_miles_rt = 0;
		var rent_charge = 0;
		if(lease_miles == 8) {
			lease_miles_rt = 2.4 * 1500;
		}
		if(lease_residual > 0) {
			price_residual = (lease_residual / 100) * loan_amount;
		}
		if(lease_interest > 0) {
			rent_charge = parseInt(price_final) + parseInt(price_residual);
			rent_charge = price_residual * lease_interest;
		}
		var monthly_payment = (price_residual + parseInt(lease_miles_rt)) / lease_term + parseInt(rent_charge);
		monthly_payment = monthly_payment.toFixed(2);
		$(".lease_month-price-results .price").html(currency_symbol + monthly_payment);
		$(".lease_month-rt").html(lease_term);
		$(".lease_list-price").html('' + currency_symbol + price_final + '');
		$(".lease_list-down").html('' + currency_symbol + down_payment + '');
		$(".lease_mileage").html('' + currency_symbol + lease_miles_rt + '');
		$(".residual_number").html('' + currency_symbol + lease_residual + '');
		$(".lease_residual").html('' + currency_symbol + price_residual + '');
		$(".lease_list-totals-loan").html('' + currency_symbol + monthly_payment + '');
	}
	$('.lease_do_calculator_clear').click(function() {
		$('#lease_cash_down').val('0');
		$('#lease_interest').val('0.00183');
		$('#lease_residual').val('50');
		$("#lease_miles option").removeAttr("selected");
		$("#lease_miles option:nth-child(1)").attr("selected", "selected");
		$("#lease_score_credit option").removeAttr("selected");
		$("#lease_score_credit option:nth-child(1)").attr("selected", "selected");
		$("#lease_term option").removeAttr("selected");
		$("#lease_term option:nth-child(1)").attr("selected", "selected");
		$("#lease_term").trigger("change");
		$("#lease_score_credit").trigger("change");
		$(".lease_do_calculator").trigger("click");
		calculator_lease_form();
	});
	$(document).on('click', '.lease_do_calculator', function() {
		calculator_lease_form();
	});
    $(window).on('load', function(){
		calculator_finance_form();
		calculator_lease_form();
	});
	$('#jws_submit_review .button').on('click', function(e) {
		e.preventDefault();
		if(!$(this).hasClass('disabled')) {
			$.ajax({
				url: jws_ajax_url,
				dataType: 'json',
				context: this,
				method: 'post',
				data: $(this).closest('form').serialize() + '&action=jws_submit_review',
				beforeSend: function() {
					$(this).addClass('form-loader');
					$(".jws-dealer-note").slideUp("normal", function() {
						$(this).remove();
					});
				},
				success: function(data) {
					$(this).removeClass('form-loader');
					if(data.updated) {
						window.location.href = data.updated;
						location.reload();
					} else {
						var html = '<ul class="jws-dealer-note red"><li>' + data.message + '</li></ul>';
						$('.jws-write-dealer-review').append(html);
						$('.jws-dealer-note').hide().slideDown();
					}
				}
			});
		}
	});

	function share_button() {
		$('.share-cars').on('click', function() {
			var parents = $(this).parents('li');
			parents.find(".addthis_inline_share_toolbox").toggleClass('opened');
			if(parents.find(".addthis_inline_share_toolbox").hasClass('opened')) {
				parents.find(".addthis_inline_share_toolbox a").delay(100).each(function(i) {
					$(this).delay(50 * i).queue(function() {
						$(this).addClass("show");
						$(this).dequeue();
					});
				});
			} else {
				parents.find(".addthis_inline_share_toolbox a").removeClass('show');
			}
		});
	}
	share_button();

	function car_featured_slider() {
		$('.cars-featured-slider').not('.slick-initialized').slick({
			dots: false,
			arrows: true,
			prevArrow: '<span class="jws-carousel-btn prev-item"><i class="jws-icon-arrow_carrot-left"></i></span>',
			nextArrow: '<span class="jws-carousel-btn next-item "><i class="jws-icon-arrow_carrot-right"></i></span>',
			swipeToSlide: true,
		});
	}
	car_featured_slider();

	function car_related_slider() {
		$('.car-related-slider ').not('.slick-initialized').slick({
			dots: false,
			arrows: true,
			prevArrow: '<span class="jws-carousel-btn prev-item"><i class="jws-icon-arrow_carrot-left"></i></span>',
			nextArrow: '<span class="jws-carousel-btn next-item "><i class="jws-icon-arrow_carrot-right"></i></span>',
			swipeToSlide: true,
		});
	}
	car_related_slider();

	function car_sidebar() {
		$('.toggle-cars-sidebar  ').on('click', function() {
			$('.cars-sidebar').toggleClass('active');
		});
		$(document).on("click", function(e) {
			if($(e.target).is(".listing-sidebar,.listing-sidebar *,.toggle-cars-sidebar,.toggle-cars-sidebar *, .remove-cars-value *") === false) {
				$('.cars-sidebar').removeClass('active');
			}
		});
	}
	car_sidebar();
	$(document).on('click', '.jws-make-features', function() {
		var Id = $(this).data('id'),
			btn = $(this);
		btn.toggleClass('active');
		var data = {
			id: Id,
			action: "jws_ajax_load_make_features",
		};
		$.ajax({
			url: jws_ajax_url,
			data: data,
			method: 'get',
			success: function() {},
			error: function() {
				console.log('error');
			},
		});
	});
})(jQuery);