/* JS di gestione della ricerca veloce auto-complete in Ajax */

function AS_Init()
{
    
    $(".AjaxSearchInputBox").autocomplete(
		"ajax_search.php",
		{
            delay:500,
			minChars:2,
			matchSubset:0,
			matchContains:1,
			cacheLength:10,
			autoFill:false,
			selectFirst: true,
			onItemSelect:AS_SelectItem,
			onFindValue:AS_FindValue,
			formatItem:AS_FormatItem
		}
	);

    
	$(".AjaxSearchInputBox").focus(function () {
        var SearchType = $(this).attr("searchtype");
        $(this).setOptions({
            extraParams: { searchType : SearchType }
        });
    });
    

    /*
    Popola i campi voluti con il risultati
    I campi da popolare si devono chiamare come il campo della ricerca
    con estensione _valN. Ad esempio se il campo su cui viene effettuata la
    ricerca si chiama search, allora i campi da popolare si devono chiamare
    search_val1, search_val2, etc. (Massimo 5).
    Il valore viene restituito sotto forma di stringa con i 5 valori separati
    da un cancelleto #, Quindi questa funzione esplode il valore e trova i singoli 
    */
    $(".AjaxSearchInputBox").result(
        function(event, data, formatted) {
            var FieldName = '';
            var frm = this.form;
            var fld = ''
    		if (data) {
                $values_array = data[1].split('#');
                for (i=1; i<$values_array.length; i++) {
                    FieldName = $(this).attr("name")+"_val"+i;
                    fld = frm.elements[FieldName];
                    if (fld) { fld.value = $values_array[i]; }
                }
            
            }
        }
    );
    
}

function AS_FindValue(li) {

       
	if( li == null ) return alert("DA TRADURRE: nessun elemento trovato");

	// if coming from an AJAX call, let's use the CityId as the value
	if( !!li.extra ) var sValue = li.extra[0];

	// otherwise, let's just display the value in the text box
	else var sValue = li.selectValue;

	alert("The value you selected was: " + sValue);
	
}


function AS_SelectItem(li) {
	AS_findValue(li);
}

function AS_FormatItem(row) {
	return row[0];
}

function AS_ResetBox(Btn) {
    var BtnContainer = Btn.parentNode.parentNode;
	$(BtnContainer).find('input').each(function (i) {
		this.value = '';
	});
}

function AS_SetType(Type) {
    
}
