var count_hits_time_out = 0;

$(document).ready(function() {
	$('#hits_counter').show().find('a').click(function() {
		$('#vehicle_search').get(0).submit();
		return false;
	});

	if ($.browser.msie && parseInt($.browser.version) == 6)
	{
		var offset =
			$('#hits_counter')
				.css('position', 'absolute')
				.offset();
		var hits_counter_top = offset.top;

		$(window)
			.scroll(function() {
				var top =
					document.documentElement.scrollTop + hits_counter_top;

				$('#hits_counter').css('top', top + 'px');
			});
	}

//	$('#footer').before('<textarea id="monitor">123456</textarea>');

	// gombok beállítása
	$('.common_submit').hide();
	$('.custom_submit').show().find('a').click(function() {
		$('#vehicle_search').get(0).submit();
		return false;
	});;

	// kategória kiválasztó beállítása
	$('input:radio[name=body_type_mode]')
		.click(function() {
			update_body_type_mode_selectors($(this).attr('id'));
			count_hits();
		})
		.filter(':checked').each(function() {
			update_body_type_mode_selectors($(this).attr('id'));
		});

	// checkbox tagek beállítása
	$('input:checkbox')
		.click(function() {
			count_hits();
		})
		.filter('[name^=body_type_').click(function() {
			if (this.checked)
				set_body_type_mode_user_select_to_active();
			else
				test_body_type_option_is_enabled();
		});

	$('input[name=price_type]').click(function() {
			count_hits();
		});

	// gyártmány/modell kiválasztó beállítása
	for (i = 0; i < 3; ++ i)
	{
		$('#model' + i).replaceWith(
			'<select id="model' + i + '" name="model' + i + '" class="common select"></select>');
		var make = $('#make' + i);
		var model = $('#model' + i);
		var model_id = $('#model' + i + '_value_holder').val();
		model.change(function() {
			var id = $(this).attr('id').match(/\d$/);
			$('#model' + id + '_value_holder').val($(this).val());
		})
		setup_make_selector(make, model, model_id);
		make.click();
	}

	// select tagek beállítása
	$('select').change(function() {
		count_hits();
	})

	// text input tagek beállítása
	var text_time_out = 0;
	$('input[type=text]').keypress(function(e) {
		if (text_time_out) clearTimeout(text_time_out);
		text_time_out = setTimeout(count_hits, 350);
	});

	// model_description input beállítása
	var model_description_time_out = 0;
	$('#model_description0').keypress(function(e) {
		if (model_description_time_out)
			clearTimeout(model_description_time_out);
		model_description_time_out = setTimeout(adjust_make_fields, 350);
	});


	$('input[type=text]').blur(function(e) {
		if (text_time_out) clearTimeout(text_time_out);
	});

	/*
	Egyenlőre az API-ban csak ország alapján lehet keresni
	// location kiválasztók beállítása
	$('#location_country').change(function() {
		if ($(this).val() == 'DE')
			$('#location_radius').attr('disabled', false);
		else
			$('#location_radius').attr('disabled', true).val('all');

		$('#location_zip').val('');
	}).change();
	*/

	// találatok számának lekérdezése
	count_hits();
});

function update_body_type_mode_selectors(checked_id)
{
	if (checked_id == 'body_type_mode_all')
		set_body_type_mode_all_to_active();
	else //if (checked_id == 'body_type_mode_user_select')
		set_body_type_mode_user_select_to_active();
}

function set_body_type_mode_all_to_active()
{
	$('#body_type_mode_all').attr('checked', true);
	$('#body_type_mode_user_select').attr('checked', false);

	$('#body_type_mode_all_label').addClass('emphasized');
	$('#body_type_mode_user_select_label').removeClass('emphasized');

	disable_body_type_options();
}

function set_body_type_mode_user_select_to_active()
{
	$('#body_type_mode_all').attr('checked', false);
	$('#body_type_mode_user_select').attr('checked', true);

	$('#body_type_mode_all_label').removeClass('emphasized');
	$('#body_type_mode_user_select_label').addClass('emphasized');
}

function test_body_type_option_is_enabled()
{
	if ($('#body_type_options input:checked').length == 0)
		set_body_type_mode_all_to_active();

}

function disable_body_type_options()
{
	$('#body_type_options input:checked').attr('checked', false);
}

/**
 * gyártmány/modell kiválasztó beállítása
 *
 * @param		make: DOM objectum, gyártmány select mező
 * @param		model: DOM objectum, modell select mező
 * @param		model_id: string, modell azonosító
 */
function setup_make_selector(make, model, model_id)
{
	model.attr('disabled', 1);
	var last_val = 'all';
	make.change(function() {
			var val = make.val();
			if (val == last_val)
			{
				return;
			}
			else if (val == 'all')
			{
				model.attr('disabled', 1);
				model.html('<option>&nbsp;</option>');
			}
			else
			{
				model.attr('disabled', 1);
				model.html('<option>Betöltés...</option>');
				setTimeout(function() {
					$.get("retrieve_models.php",
						{make: val, model: model_id},
						function(data){
							model.html(data);
							model.attr('disabled', 0);
							count_hits()
						});
					}, 50);
			}
			last_val = val;

			adjust_make_fields();
		});

	if (make.val() != 'all' && model_id) make.change();
}

function adjust_make_fields()
{
	if ($('#model_description0').val() == '')
		$('#make1,#make2').attr('disabled', false);
	else
		$('#make1,#make2').attr('disabled', true).val('all');

	if ($('#make1').val() == 'all'
		&& $('#make2').val() == 'all')
		$('#model_description0').attr('disabled', false);
	else
		$('#model_description0').attr('disabled', true).val('');
}

function count_hits()
{
	$('#hits_counter').find('div.button').hide()
		.end().find('div.ajaxload').show();

	if (count_hits_time_out) clearTimeout(count_hits_time_out);

	count_hits_time_out = setTimeout(function() {
		var search_type = $('#search_type').val();
		var is_new = search_type == 'N';
		var is_export = search_type == 'E';

		url = 'type=' + $('#type').val();
		url += '&search_type=' + search_type;

		url += '&page_number=' + $('#page_number').val();
		url += '&sort_field=' + $('#sort_field').val();
		url += '&sort_order=' + $('#sort_order').val();

		$('#body_type_options input:checked').each(function() {
			url += '&body_type[]=' + $(this).val();
		});

		url += '&make0=' + $('#make0').val();
		url += '&model0=' + $('#model0').val();
		url += '&model_description0=' + $('#model_description0').val();

		url += '&make1=' + $('#make1').val();
		url += '&model1=' + $('#model1').val();
		url += '&model_description1=' + $('#model_description1').val();

		url += '&make2=' + $('#make2').val();
		url += '&model2=' + $('#model2').val();
		url += '&model_description2=' + $('#model_description2').val();

		if (! is_new)
		{
			url += '&year_from=' + $('#year_from').val();
			url += '&year_to=' + $('#year_to').val();

			url += '&mileage_from=' + $('#mileage_from').val();
			url += '&mileage_to=' + $('#mileage_to').val();

			url += '&damaged_vehicle=' + $('#damaged_vehicle').val();

			url += '&usage_type=' + $('#usage_type').val();
		}

		url += '&price_type=' + (is_export
				? $('input[name=price_type]:checked').val() : 'gross');

		url += '&power_from=' + $('#power_from').val();
		url += '&power_to=' + $('#power_to').val();

		url += '&price_from=' + $('#price_from').val();
		url += '&price_to=' + $('#price_to').val();

		url += '&vat_reclaimable='
			+ ($('#vat_reclaimable:checked').length > 0 ? 1 : 0);

		url += '&fuel=' + $('#fuel').val();
		url += '&gearbox_operation=' + $('#gearbox_operation').val();

		url += '&location_country=' + $('#location_country').val();
		url += '&location_zip=' + $('#location_zip').val();
		url += '&location_radius=' + $('#location_radius').val();

		url += '&climate_control=' + $('#climate_control').val();

		$('input[name^=comfort_and_interior],'
		+ 'input[name^=exterior],'
		+ 'input[name^=security_and_environment],'
		+ 'input[name^=special_vehicles],'
		+ '#metallic_coat')
			.filter(':checked').each(function() {
				url += '&' + $(this).attr('name') + '=' + $(this).val();
			});

		$('input[name^=base_color]')
			.filter(':checked').each(function() {
				url += '&base_color[]=' + $(this).val();
			});

		url += '&emission_class=' + $('#emission_class').val();
		url += '&emission_sticker=' + $('#emission_sticker').val();
		url += '&advertisement_type=' + $('#advertisement_type').val();
		url += '&date_of_entry=' + $('#date_of_entry').val();
		url += '&doors_count=' + $('#doors_count').val();
		url += '&seats_count=' + $('#seats_count').val();

		url = url.replace(/=(all|null|undefined)/g, '=');

//		$('#monitor').val(url);

		$.get('count_hits.php?' + url, {},
			function(data){
//				alert(data);
				$('#hits_counter strong,.custom_submit strong').html(
					format_number(data));
				$('#hits_counter').find('div.button').show()
					.end().find('div.ajaxload').hide();
			});
	}, 300);
}

function _count_hits()
{
	$('#hits_counter').find('div.button').hide()
		.end().find('div.ajaxload').show();

	if (count_hits_time_out) clearTimeout(count_hits_time_out);

	count_hits_time_out = setTimeout(function() {
		var url = 'isSearchRequest=true&switchScenario='
			+ '&sortOption.sortOrder=ASCENDING&lang='
			+ '&scopeId=C&_features=on&bodyStyleRadio=';

		var sort_by = 'price.consumerGrossEuro';

		var search_type = $('#search_type').val();
		var is_new = search_type == 'N';
		var is_export = search_type == 'E';

		if (! is_export) url += '&negativeFeatures=EXPORT';

		$('#body_type_options input:checked').each(function() {
			url += '&categories=' + $(this).val();
		});

		url += '&makeModelVariant1.makeId=' + $('#make0').val();
		url += '&makeModelVariant1.modelId=' + $('#model0').val();
		url += '&makeModelVariant1.modelDescription='
				+ $('#model_description0').val();

		url += '&makeModelVariant2.makeId=' + $('#make1').val();
		url += '&makeModelVariant2.modelId=' + $('#model1').val();
		url += '&makeModelVariant2.modelDescription='
				+ $('#model_description1').val();

		url += '&makeModelVariant3.makeId=' + $('#make2').val();
		url += '&makeModelVariant3.modelId=' + $('#model2').val();
		url += '&makeModelVariant3.modelDescription='
				+ $('#model_description2').val();

		if (is_new)
		{
			url += '&usage=NEW';
		}
		else
		{
			url += '&minFirstRegistrationDate=' + $('#year_from').val();
			url += '&maxFirstRegistrationDate=' + $('#year_to').val();

			url += '&minMileage=' + $('#mileage_from').val();
			url += '&maxMileage=' + $('#mileage_to').val();

			url += '&damageUnrepaired=' + $('#damaged_vehicle').val();

			url += '&usageType=' + $('#usage_type').val();

			if (is_export)
			{
				var price_type = $('input[name=price_type]:checked').val();
				if (price_type == 'net')
				{
					sort_by = 'searchNetGrossPrice';
					url += '&grossPrice=false';
				}
				else
					url += '&grossPrice=true';
			}

		}

		url += '&sortOption.sortBy=' + sort_by;


		url += '&minPowerAsArray=' + $('#power_from').val();
		url += '&minPowerAsArray=KW';

		url += '&maxPowerAsArray=' + $('#power_to').val();
		url += '&maxPowerAsArray=KW';

		url += '&minPrice=' + $('#price_from').val();
		url += '&maxPrice=' + $('#price_to').val();

		if ($('#vat_reclaimable:checked').length > 0)
			url += '&vatable=true';

		url += '&fuel=' + $('#fuel').val();
		url += '&transmission=' + $('#gearbox_operation').val();

		url += '&ambitCountry=' + $('#location_country').val();
		url += '&zipcode=' + $('#location_zip').val();
		url += '&zipcodeRadius=' + $('#location_radius').val();

		url += '&climatisation=' + $('#climate_control').val();

		$('input[name^=comfort_and_interior],'
		+ 'input[name^=exterior],'
		+ 'input[name^=security_and_environment],'
		+ 'input[name^=special_vehicles],'
		+ '#metallic_coat')
			.filter(':checked').each(function() {
				url += '&features=' + $(this).val();
			});

		$('input[name^=base_color]')
			.filter(':checked').each(function() {
				url += '&colors=' + $(this).val();
			});

		url += '&emissionClass=' + $('#emission_class').val();
		url += '&adLimitation=' + $('#advertisement_type').val();
		url += '&daysAfterCreation=' + $('#date_of_entry').val();
		url += '&doorCount=' + $('#doors_count').val();

		url = url.replace(/=all/g, '=');
		url = url.replace(/=null/g, '=');
		url = 'http://suchen.mobile.de/fahrzeuge/hitscounter.html?' + url;

		//$('#monitor').val(url);

		$.get('count_hits.php', {url: url},
			function(data){
				$('#hits_counter strong,.custom_submit strong').html(
					format_number(data));
				$('#hits_counter').find('div.button').show()
					.end().find('div.ajaxload').hide();
			});
	}, 350);
}
