// ===================================================================================
// Codice jQuery da applicare alle dropdown per:
//  - trasformarle in text autocomplete 
//  - personalizzarle graficamente ad esempio come le text
//
// Versione 1.0 Jessica Mammarella
//
// === === === === === ===
// - Necessario includere anche il file jquery.autocomplete.js
// - Stylesheet di riferimento ea_combobox.css
// === === === === === ===
// - Per trasformare una dropdown in text autocomplete applicare la classe "autocomplete"
// - Per trasformare una dropdown in similtext applicare la classe "customstyle"
// === === === === === ===
// 
// ===================================================================================

// ===================================================================================
// FUNZIONI AUTOCOMPLETE
// ===================================================================================

// Modificato il valore di una select aggiorno la relativa text autocomplete
function updateDropdown(thisDrpDwn) {
	createDropDown($("#" + thisDrpDwn));
	$("#" + thisDrpDwn + "_text").result(function (event, data, formatted) { changeDropDown($(this)); });
	$("#" + thisDrpDwn + "_text").blur(function (event, data, formatted) { changeDropDown($(this)); });
	$("#" + thisDrpDwn + "_text").focus(function () { $(this).click(); $(this).select(); })
	$("#" + thisDrpDwn + "_text").click(function () { $(this).select(); })
	$("#" + thisDrpDwn + "_text").mouseup(function (e) { e.preventDefault(); });
}

// Modificato il valore di default di una select aggiorno solo il testo di una text autocomplete già caricata
function updateText(thisDrpDwn) {
	var textId = thisDrpDwn.attr('id');
	$("#" + textId + "_text").attr('value', thisDrpDwn.find("option:selected").text());
}

// Modificato il valore di una text autocomplete aggiorno la relativa select
function changeDropDown(thisDrpDwn) {
	var textId = thisDrpDwn.attr('id');
	$("#" + textId).addClass('ac_loading');
	var selectId = textId.substring(0, textId.length - 5);
	$('#' + selectId + ' option').eq("").attr('selected', 'selected');
	if (thisDrpDwn.val().length != 0) { $('#' + selectId).searchValue(thisDrpDwn.val()); }
	$("#" + selectId).change(); // evento onchange della select
	$("#" + textId).removeClass('ac_loading');
}

// Creo o aggiorno la text autocomplete indicata
function createDropDown(combobox) {
	if (!$.browser.msie || ($.browser.msie && $.browser.version > 6)) {
		var comboboxId = combobox.attr('id'); // select id
		var selected = combobox.find("option:selected"); // select valore selezionato
		var comboboxOptions = $("option", combobox); // select valori

		var dropdownId = comboboxId + "_text"; // dropdown autocomplete id
		var dropdownName = combobox.attr('name'); // dropdown autocomplete name

		var requiredAttr = ""; var disabledAttr = ""; var disabledClass = ""; var validClass = "";

		if (dropdownName.length == 0) dropdownName = dropdownId;

		if (combobox.attr('requiredField') != null && combobox.attr('requiredField').length != undefined) { requiredAttr = 'requiredField="' + combobox.attr('requiredField') + '"'; }
		if (combobox.attr('disabled') == true) { disabledAttr = 'disabled'; disabledClass = "inputdisabled"; }

		if ($("#" + dropdownId).length == 0) $('<input type="text" id="' + dropdownId + '" name="' + dropdownName + '" class="dropdown ' + combobox.attr('class') + disabledClass + '" ' + requiredAttr + ' ' + disabledAttr + '/>').insertAfter('#' + comboboxId);
		combobox.attr('class', 'none'); //nascondo la select
		var dropdown = $("#" + dropdownId); // dropdown
		dropdown.attr('value', selected.text());
		var dropdownOptions = "";
		comboboxOptions.each(function () { if ($(this).text() && $(this).val()) { dropdownOptions += $(this).text() + "|"; } });  // costruisco elenco valori per la text autocomplete
		createMenu(dropdownOptions, dropdownId, "");

	}
}

// Creo fisicamente una text autocomplete
function createMenu(listName, elementName, filterValue) {
	listName = listName.substring(0, listName.length - 1);
	$("#" + elementName).unautocomplete().autocomplete((listName + filterValue).split("|"),
    { minChars: 0, delay: 0, mustMatch: true, matchContains: false,
    	autoFill: true, scroll: true
    });
}

// Aggiorno l'elenco dei dati di una select 
function populateDropdown(select, data) {
	$("option", select).each(function (i, option) { $(option).remove(); });
	$.each(data, function (i, item) { select.append($('<option></option>').val(item.Value).html(item.Text)); });
	updateDropdown(select.attr('id'));
}

// Clean campi collegati
function cleanLinked(toClean) {
	var textToClean = toClean.split("|");
	$.each(textToClean, function (i) {
		$("#" + textToClean[i]).attr('value', '');
		$("#" + textToClean[i] + "_text").attr('value', '');

		$("#" + textToClean[i]).removeAttr('disabled');
		$("#" + textToClean[i]).removeClass("inputdisabled");

		$("#" + textToClean[i] + "_text").removeAttr('disabled');
		$("#" + textToClean[i] + "_text").removeClass("inputdisabled");

		if ($("#" + textToClean[i]).attr('type') == "select-one") populateDropdown($("#" + textToClean[i]), "");
	});
}

// Clean campi collegati
function checkItaly(toClean) {
	var textToClean = toClean.split("|");
	$.each(textToClean, function (i) {
		if ($("#" + textToClean[i] + "_text").length == 0) {
			$("#" + textToClean[i]).attr('disabled', true);
			$("#" + textToClean[i]).addClass('inputdisabled');
		}
		else {
			$("#" + textToClean[i] + "_text").attr('disabled', true);
			$("#" + textToClean[i] + "_text").addClass('inputdisabled');
		}
	});
}

// Aggiorna campi collegate
function updateLinked(destination, functionTocall, filter, toClean) {
	$("#" + destination + "_text").addClass('ac_loading');
	cleanLinked(toClean);

	if (toClean.indexOf("Provincia") >= 0) if (filter.toUpperCase() != "ITALIA") checkItaly(toClean);

	if (filter != undefined && filter.length != 0) {
		$.ajax({
			url: functionTocall + filter,
			async: false,
			dataType: 'json',
			success: function (data) {
				if ($("#" + destination).attr('type') == "text")
					$("#" + destination).attr('value', data);
				else
					populateDropdown($("#" + destination), data);
			}
		});
	}
	$("#" + destination + "_text").removeClass('ac_loading');
}

$.fn.searchValue = function (value) {
	$(this).each(function () {
		$('option', this).each(function () {
			if ($(this).text().toLowerCase() == value.toLowerCase()) {
				$(this).attr('selected', 'selected');
			};
		});
	});
}

// ===================================================================================
// FUNZIONI CUSTOM STYLE
// ===================================================================================


$.fn.extend({

	customStyle: function (options) {
		if (!$.browser.msie || ($.browser.msie && $.browser.version > 6)) {
			return this.each(function () {

				var currentSelected = $(this).find(':selected');
				$(this).after('<span><input class="ac_input" value="' + currentSelected.text() + '" id="' + $(this).attr('id') + '_text" readonly /></span>').css({ position: 'absolute', opacity: 0, 'z-index': 20 });
				var selectBoxSpan = $(this).next();
				var selectBoxSpanInner = selectBoxSpan.find(':first-child');
				selectBoxSpan.css({ display: 'inline-block' });
				if ($.browser.msie) {
					$(this).css({ 'margin-left': '2px' });
					selectBoxSpan.css({ 'margin-left': '-3px' });
				}
				selectBoxSpanInner.css({ display: 'inline-block' });
				$(this).change(function () {
					selectBoxSpanInner.val($(this).find("option:selected").text());
				});

			});
		}
	}
});

function checkValidate() {
	var theForm = combobox.closest("form");
	theForm.submit(function (e) {
		var val = theForm.validate();
		//val.showErrors();
		formValid = val.valid();
		if (formValid == true) { return true; }
		else {
			$(".autocomplete").each(function () {
				if ($(this).hasClass('input-validation-error')) { $("#" + dropdownId).addClass("input-validation-error"); }
			});
		};

		e.preventDefault();
	});
}

// Aggiorna campi collegate
function updateLinkedCombo(destination, functionTocall, filter, toClean) {
	$("#" + destination + "_text").addClass('ac_loading');
	cleanLinkedCombo(toClean);

	if (filter != undefined && filter.length != 0) {
		$.ajax({
			url: functionTocall + filter,
			async: false,
			dataType: 'json',
			success: function (data) {
				populateDropdownCombo($("#" + destination), data);

				$("#" + destination + "_text").attr('value', $("#" + destination).find("option:selected").text());
			} 
		});
	}

	$("#" + destination + "_text").removeClass('ac_loading');
}

// Clean campi collegati
function cleanLinkedCombo(toClean) {
	var textToClean = toClean.split("|");
	$.each(textToClean, function (i) {

		$("#" + textToClean[i]).attr('value', '');
		$("#" + textToClean[i] + "_text").attr('value', '');
		$("#" + textToClean[i] + "_text").removeAttr('disabled');
		$("#" + textToClean[i] + "_text").removeClass("inputdisabled");

		if ($("#" + textToClean[i]).attr('type') == "select-one") populateDropdownCombo($("#" + textToClean[i]), "");
	});

}

// Aggiorno l'elenco dei dati di una select 
function populateDropdownCombo(select, data) {
	$("option", select).each(function (i, option) { $(option).remove(); });
	var optionHtml = "";
	$.each(data, function (i, item) { optionHtml += '<option value="' + item.Value + '">' + item.Text + '</option>' });
	select.html(optionHtml);
}

// ===================================================================================
// TRASFORMAZIONE
// ===================================================================================

$(document).ready(function () {

	/* ======= autocomplete ======= */

	// Trasformazione automatica di tutte le dropdown in text autocomplete
	$(".autocomplete").each(function () { createDropDown($(this)); });

	// Gestione evento onchange delle text autocomplete per aggiornare la relativa select
	$(".dropdown").result(function (event, data, formatted) { changeDropDown($(this)); });
	$(".dropdown").blur(function (event, data, formatted) { changeDropDown($(this)); });

	// Sull'onfocus  delle text apro automaticamente la tendina
	$(".dropdown").focus(function () { $(this).click(); $(this).select(); })
	$(".dropdown").click(function () { $(this).select(); });
	$(".dropdown").mouseup(function (e) { e.preventDefault(); });

	$('.ac_results').css('width', 'auto');

	/* =========================== */

	/* ======= customstyle ======= */
	$('.customstyle').customStyle();
	/* =========================== */

});

$(document).ready(function () {

	$('form').each(function () { 
		$(this).submit(function (e) {
		var val = $(this).validate();
		formValid = val.valid();
		if (formValid == true) { return true; }
		else {
			$(".autocomplete").each(function () {
				if ($("#" + $(this).attr('name')).hasClass("input-validation-error")) { $(this).addClass("input-validation-error"); }
			});
		};

		e.preventDefault();
		})
	});

});
