$(function() {
  
    var //url = "http://autocomplete.pgol.it/web/search.php",
        url='http://autocomplete.pgol.it/web/search_tmp.php',
        closeDiv = "<a href='javascript:void(0);' title='chiudi' id='ac_close'><div class='close_cloud'></div></a>",
        numCharsRGS = 20;
    
    $("#cosa,#numero").focus().autocomplete(url, {
        selectFirst: false,
        minChars:3,
        delay:50,
        cacheLength:0,
        matchContains:false,
        matchSubset:true,
        matchCase:false,
        max:10,
        dataType:'jsonp',
        url:url,
        autoFill:false,
        close:closeDiv,
        target:"#ac_target",
	      resultsClass: "autocompl_cloud round-box clearfix",
        // Format the data that gets put in the input field
        formatResult: function(row) {
          return (row.tel && row.tel !== '') ? row.tel : row.res;
        },
        // Format the individual row in the drop-down
        formatItem:function(row) {
          return (row.tel && row.tel !== '') ? row.tel + ' - ' + 
            // Concat RGS if over max char length
            ((row.rgs.length > numCharsRGS) ? row.rgs.substring(0, numCharsRGS) + '...' : row.rgs)
            : row.res;
        },
        parse: function(data){
            var objArray = data.results,
                parsed = [],
                i,
                value;
            for (i=0; i < objArray.length; i+=1) {
                rawValue = objArray[i];
                value = this.formatMatch(rawValue, i+1, objArray.length);
                parsed[parsed.length] = {
                    data: rawValue,
                    value: value,
                    result: this.formatResult && this.formatResult(rawValue) ||
                    value
                }
            }
            return parsed;
        }
    });
    
    //Log redsheriff sull'autocomplete
    $("#cosa,#numero").result(
        function(e, a, b){
        	var x = new SEAT.LogRedSheriff();
          x.logRedSheriff("PG-AUTOCOMPLETE");
        }
    );

    $("#ac_close").click(function() {
        $(":input").unautocomplete();
    });

    $.ajaxSetup({
        cache: true,
        dataType: 'jsonp',
        timeout: 30000, // Timeout of 30 seconds
        type: 'GET',
        url: url
    });
});