
var formCheckboxesArr = [ "carrozzeria", "posti", "alimentazione", "omologazione", "cambio", "trazione", "marche" ];
var formOptionsArr = [
	{ button: "consumo", selects: [ "consmin", "consmax" ] },
	{ button: "potenza", selects: [ "potmin", "potmax" ] },
	{ button: "dimensioni", selects: [ "dimLungmin", "dimLungmax", "dimLarghmin", "dimLarghmax", "dimAltezmin", "dimAltezmax" ] },
	{ button: "prezzo", selects: [ "prezzomin", "prezzomax" ], checks: [ "prezzooltre" ] },
	{ button: "emiss", selects: [ "co2min", "co2max" ] },
	{ button: "velocita", selects: [ "velmin", "velmax" ] },
	{ button: "accelerazione", selects: [ "accmin", "accmax" ] },
	{ button: "bagagliaio", selects: [ "bagmin", "bagmax" ] },
	{ button: "cilindrata", selects: [ "cilmin", "cilmax" ] }
];

var advRequestCounter = 0;

/////////////////

function createRemoveableParamElem(text, names, values) {
	values = typeof(values) != 'undefined' ? values : text;
	return $("<li>").append(
		$('<a href="javascript:void(0)" class="delete"></a>').html(upperFirst(text)).click(function() {
			var $this = $(this);
			
			if (typeof(names) == "object") {
				for (var i = 0; i < names.length; i++) {
					$("#paramsForm select[name='" + names[i] + "'] option[class~='default']").attr("selected", "selected");
					$("#paramsForm select[name='" + names[i] + "'] option:not([class~='default'])").attr("selected", "");
					$("#paramsForm select[name='" + names[i] + "']").change();
				}
			} else {
				$("#paramsForm input[name='" + names + "'][value='" + values + "']").attr("checked", "");
				var $input = $("#paramsForm input[name='" + names + "'][value='" + values + "']");
				$input.change();
				$input.parent().parent().removeClass("active");
			}
			
			setParamsButtonInitState();
			
			$this.parent().remove();
			if ($("#removeableParams li").length == 0) {
				$("#removeableParamsBox").hide();
			}
			
			updateCarsCounter();
			sendParamsForm(1);
		})
	);
}

/////////////////

function areDefaultsParams() {
	return $("#paramsForm input[type='checkbox']:checked").length == 0 &&
		$("#paramsForm select option:not([class~='default']):selected").length == 0;
}

function getParametersData() {
	var data = { };
	
	$("#paramsForm input[type='checkbox']:checked").each(function() {
		if (data[this.name] != null)
			data[this.name] += "," + this.value;
		else
			data[this.name] = this.value;
	});
	$("#paramsForm select option:not([class~='default']):selected").each(function() {
		data[this.parentNode.name] = this.value;
	});
	
	return data;
}

function initializeMenu() {
	$(".qrt-param .btn_listino a").click(function() {
		$('.qrt-param .btn_listino a.btn_listino_active').addClass("btn_listino_normal").removeClass("btn_listino_active");
		$(this).addClass("btn_listino_active");
		setParamsButtonInitState();
		
		var id = $(this).attr('id');
		var $curBoxes = $(".boxParametri:not(:hidden)");
		var $selBox = $('#box-' + id);
		
		if ($curBoxes.length != 1 || $curBoxes[0] !== $selBox[0]) {
			if ($curBoxes.length > 0) {
				// in sequenza
				$curBoxes.slideUp("slow", function() {
					$selBox.slideDown("slow");
				});
				// insieme
				/*$curBoxes.slideUp("slow");
				$selBox.slideDown("slow");*/
			} else {
				$selBox.slideDown("slow");
			}
		}
	});
}

function navigate() {
	sendParamsForm();
}

function navigateToPage(pageN) {
	sendParamsForm(pageN);
}

function populateRemoveableParams() {
	var $remsUl = $("#removeableParams");
	var $remsBox = $("#removeableParamsBox");
	$remsUl.children().remove();
	
	var $a, text;
	
	$("#paramsForm input[name='carrozzeria']:checked").each(function(idx) {
		createRemoveableParamElem($(this).val(), "carrozzeria").appendTo($remsUl);
	});
	
	if ($("#paramsForm select[name='consmin'] option:not(:first):selected").length > 0 ||
		$("#paramsForm select[name='consmax'] option:not(:last):selected").length > 0) {
		text =
			"Consumo tra " + $("#paramsForm select[name='consmin'] option:selected").text() + 
			" e " + $("#paramsForm select[name='consmax'] option:selected").text() +
			" litri/100Km";
		createRemoveableParamElem(text, [ "consmin", "consmax" ]).appendTo($remsUl);
	}
	
	if ($("#paramsForm select[name='potmin'] option:not(:first):selected").length > 0 ||
		$("#paramsForm select[name='potmax'] option:not(:last):selected").length > 0) {
		text =
			"Potenza tra " + $("#paramsForm select[name='potmin'] option:selected").text() + 
			" e " + $("#paramsForm select[name='potmax'] option:selected").text();
		createRemoveableParamElem(text, [ "potmin", "potmax" ]).appendTo($remsUl);
	}
	
	if ($("#paramsForm select[name='dimLungmin'] option:not(:first):selected").length > 0 ||
		$("#paramsForm select[name='dimLungmax'] option:not(:last):selected").length > 0) {
		text =
			"Lunghezza tra " + $("#paramsForm select[name='dimLungmin'] option:selected").text() + 
			" e " + $("#paramsForm select[name='dimLungmax'] option:selected").text() +
			" cm";
		createRemoveableParamElem(text, [ "dimLungmin", "dimLungmax" ]).appendTo($remsUl);
	}
	
	if ($("#paramsForm select[name='dimLarghmin'] option:not(:first):selected").length > 0 ||
		$("#paramsForm select[name='dimLarghmax'] option:not(:last):selected").length > 0) {
		text =
			"Larghezza tra " + $("#paramsForm select[name='dimLarghmin'] option:selected").text() + 
			" e " + $("#paramsForm select[name='dimLarghmax'] option:selected").text() +
			" cm";
		createRemoveableParamElem(text, [ "dimLarghmin", "dimLarghmax" ]).appendTo($remsUl);
	}
	
	if ($("#paramsForm select[name='dimAltezmin'] option:not(:first):selected").length > 0 ||
		$("#paramsForm select[name='dimAltezmax'] option:not(:last):selected").length > 0) {
		text =
			"Altezza tra " + $("#paramsForm select[name='dimAltezmin'] option:selected").text() + 
			" e " + $("#paramsForm select[name='dimAltezmax'] option:selected").text() +
			" cm";
		createRemoveableParamElem(text, [ "dimAltezmin", "dimAltezmax" ]).appendTo($remsUl);
	}
	
	if ($("#paramsForm select[name='prezzomin'] option:not(:first):selected").length > 0 ||
		$("#paramsForm select[name='prezzomax'] option:not(:last):selected").length > 0) {
		text =
			"Prezzo tra " + $("#paramsForm select[name='prezzomin'] option:selected").text() + 
			" e " + $("#paramsForm select[name='prezzomax'] option:selected").text() +
			" &euro;";
		createRemoveableParamElem(text, [ "prezzomin", "prezzomax" ]).appendTo($remsUl);
	}
	
	if ($("#paramsForm select[name='co2min'] option:not(:first):selected").length > 0 ||
		$("#paramsForm select[name='co2max'] option:not(:last):selected").length > 0) {
		text =
			"Emissioni CO<sub>2</sub> tra " + $("#paramsForm select[name='co2min'] option:selected").text() + 
			" e " + $("#paramsForm select[name='co2max'] option:selected").text();
		createRemoveableParamElem(text, [ "co2min", "co2max" ]).appendTo($remsUl);
	}
	
	if ($("#paramsForm select[name='velmin'] option:not(:first):selected").length > 0 ||
		$("#paramsForm select[name='velmax'] option:not(:last):selected").length > 0) {
		text =
			"Velocit&agrave; tra " + $("#paramsForm select[name='velmin'] option:selected").text() + 
			" e " + $("#paramsForm select[name='velmax'] option:selected").text() +
			" Km/h";
		createRemoveableParamElem(text, [ "velmin", "velmax" ]).appendTo($remsUl);
	}
	
	$("#paramsForm input[name='posti']:checked").each(function(idx) {
		text = $(this).parent().text() + " Posti";
		createRemoveableParamElem(text, "posti", $(this).val()).appendTo($remsUl);
	});
	
	$("#paramsForm input[name='alimentazione']:checked").each(function(idx) {
		text = upperFirst($(this).parent().text());
		createRemoveableParamElem(text, "alimentazione", $(this).val()).appendTo($remsUl);
	});
	
	$("#paramsForm input[name='omologazione']:checked").each(function(idx) {
		text = upperFirst($(this).parent().text());
		createRemoveableParamElem(text, "omologazione", $(this).val()).appendTo($remsUl);
	});
	
	if ($("#paramsForm select[name='accmin'] option:not(:first):selected").length > 0 ||
		$("#paramsForm select[name='accmax'] option:not(:last):selected").length > 0) {
		text =
			"Accelerazione tra " + $("#paramsForm select[name='accmin'] option:selected").text() + 
			" e " + $("#paramsForm select[name='accmax'] option:selected").text();
		createRemoveableParamElem(text, [ "accmin", "accmax" ]).appendTo($remsUl);
	}
	
	if ($("#paramsForm select[name='bagmin'] option:not(:first):selected").length > 0 ||
		$("#paramsForm select[name='bagmax'] option:not(:last):selected").length > 0) {
		text =
			"Bagagliaio tra " + $("#paramsForm select[name='bagmin'] option:selected").text() + 
			" e " + $("#paramsForm select[name='bagmax'] option:selected").text();
		createRemoveableParamElem(text, [ "bagmin", "bagmax" ]).appendTo($remsUl);
	}
	
	if ($("#paramsForm select[name='cilmin'] option:not(:first):selected").length > 0 ||
		$("#paramsForm select[name='cilmax'] option:not(:last):selected").length > 0) {
		text =
			"Cilindrata tra " + $("#paramsForm select[name='cilmin'] option:selected").text() + 
			" e " + $("#paramsForm select[name='cilmax'] option:selected").text();
		createRemoveableParamElem(text, [ "cilmin", "cilmax" ]).appendTo($remsUl);
	}
	
	$("#paramsForm input[name='cambio']:checked").each(function(idx) {
		text = "Cambio " + $(this).parent().text();
		createRemoveableParamElem(text, "cambio", $(this).val()).appendTo($remsUl);
	});
	
	$("#paramsForm input[name='trazione']:checked").each(function(idx) {
		text = "Trazione " + $(this).val();
		createRemoveableParamElem(text, "trazione", $(this).val()).appendTo($remsUl);
	});
	
	$("#paramsForm input[name='marche']:checked").each(function(idx) {
		text = upperFirst($(this).parent().text());
		createRemoveableParamElem(text, "marche", $(this).val()).appendTo($remsUl);
	});
	
	if ($remsUl.children().length > 0) {
		$remsBox.show();
	} else {
		$remsBox.hide();
	}
}

function selectMenuTab(tabName) {
	$("#param_" + tabName).click();
}

function prepareFilteredParamsForm() {
	$fParamsForm = $("#filteredParamsForm").html("");
	
	$("#paramsForm input[type='hidden'], #paramsForm input[type='checkbox']:checked:not([class~='ignore'])").each(function() {
		if (!(this.name == "pageN" && this.value == 1)) {
			$input = $('<input type="hidden" name="' + this.name + '">').val(this.value);
			$input.appendTo($fParamsForm);
		}
	});
	$("#paramsForm select:not([class~='ignore']) option:not([class~='default']):selected").each(function() {
		$input = $('<input type="hidden" name="' + this.parentNode.name + '">').val(this.value);
		$input.appendTo($fParamsForm);
	});
	
	return $fParamsForm;
}

function sendParamsForm(pageN, orderBy) {
	pageN = typeof(pageN) != 'undefined' ? pageN : $("#paramsForm input[name='pageN']").val();
	orderBy = typeof(orderBy) != 'undefined' ? orderBy : $("#paramsForm input[name='orderBy']").val();
	
	$("#paramsForm input[name='pageN']").val(pageN);
	$("#paramsForm input[name='orderBy']").val(orderBy);
	
	$fParamsForm = prepareFilteredParamsForm();
	$fParamsForm.submit();
}

function setParamsButtonInitState() {
	for (var i = 0; i < formCheckboxesArr.length; i++) {
		if ($("#paramsForm input[name='" + formCheckboxesArr[i] + "']:checked").length > 0) {
			$("#param_" + formCheckboxesArr[i]).addClass("btn_listino_ok"); //attr("class", "btn_listino_ok");
		} else {
			$("#param_" + formCheckboxesArr[i]).removeClass("btn_listino_ok"); //attr("class", "btn_listino_normal");
		}
	}
	
	for (var i = 0; i < formOptionsArr.length; i++) {
		var somethingSelected = false;
		
		var selects = formOptionsArr[i].selects;
		for (var l = 0; l < selects.length; l++) {
			if ($("#paramsForm select[name='" + selects[l] + "'] option:not([class~='default']):selected").length > 0) {
				somethingSelected = true;
				break;
			}
		}
		if (!somethingSelected) {
			var checks = formOptionsArr[i].checks;
			if (checks != null) {
				for (var l = 0; l < checks.length; l++) {
					if ($("#paramsForm input[name='" + checks[l] + "']:checked").length > 0) {
						somethingSelected = true;
						break;
					}
				}
			}
		}
		
		if (somethingSelected) {
			$("#param_" + formOptionsArr[i].button).addClass("btn_listino_ok"); //attr("class", "btn_listino_ok");
		} else {
			$("#param_" + formOptionsArr[i].button).removeClass("btn_listino_ok"); //attr("class", "btn_listino_normal");
		}
	}
}

function setParamsChecksInitState() {
	$("#box-param_carrozzeria input[type='checkbox']:checked").each(function() {
		$(this).parent().parent().addClass("active");
	});
	/*$("#box-param_trazione input[type='checkbox']:checked").each(function() {
		$(this).parent().parent().addClass("active");
	});*/
}

function updateCarsCounter() {
	var paramsData = getParametersData();
	
	$("#carsCounterLoader").css("visibility", "visible");
	$.ajax({
		url: "/webservices/Listino.cfm",
		dataType: "json",
		data: $.extend(paramsData, {
			"type": "countCarsByParams"
		}),
		async: true,
		success: function (data) {
			
			/* Chiamata per il refresh dei banner. */
			//refreshBanner();
			
			$("#carsCounter").html(data.TOTALCOUNT);
			$("#carsCounterLoader").css("visibility", "hidden");
			
			if (advRequestCounter++ > 0) {
				var rnd = Math.floor(Math.random() * 100001);
				var adv = '<img src="//secure-it.imrworldwide.com/cgi-bin/m?ci=domus-it&cg=0&si=http%3A//www.quattroruote.it/parametrica&rnd=' + rnd + '" alt=""/>'
				$("#carsCounterAdv").html(adv);
			}
		},
		error: function () {
			alert("Cannot get the cars count.");
			$("#carsCounterLoader").css("visibility", "hidden");
		}
	});
}

function upperFirst(str) {
	var ret = str.replace(/^\s+|\s+$/g, "");
	return ret.length > 0 ? ret.substr(0, 1).toUpperCase() + ret.substr(1) : ret;
}

