/*
 * jQuery UI Autocomplete Select First Extension
 *
 * Copyright 2010, Scott González (http://scottgonzalez.com)
 * Dual licensed under the MIT or GPL Version 2 licenses.
 *
 * http://github.com/scottgonzalez/jquery-ui-extensions
 */
//(function( $ ) {
//
//$( ".ui-autocomplete-input" ).live( "autocompleteopen", function() {
//    var autocomplete = $( this ).data( "autocomplete" ),
//        menu = autocomplete.menu;
//
//    if ( !autocomplete.options.selectFirst ) {
//        return;
//    }
//
//    menu.activate( $.Event({ type: "mouseenter" }), menu.element.children().first() );
//});
//
//}( jQuery ));

(function( $ ) {

$.ui.autocomplete.prototype.options.autoSelect = true;
$( ".ui-autocomplete-input" ).live( "blur", function( event ) {
    var autocomplete = $( this ).data( "catcomplete" );
    if ( !autocomplete.options.autoSelect || autocomplete.selectedItem ) { return; }

    var matcher = new RegExp( "^" + $.ui.autocomplete.escapeRegex( $(this).val() ) + "$", "i" );
    autocomplete.widget().children( ".ui-menu-item" ).each(function() {
        var item = $( this ).data( "item.autocomplete" );
        if ( matcher.test( item.label || item.value || item ) ) {
            autocomplete.selectedItem = item;
            return false;
        }
    });
    if ( autocomplete.selectedItem ) {
        autocomplete._trigger( "select", event, { item: autocomplete.selectedItem } );
    }
});

}( jQuery ));




//DataPicker configuration

 /*   $(function() {
        $( "#search_from" ).datepicker({
            showOn: "button",
            buttonImage: "images/calendar.gif",
            buttonImageOnly: true,
            dateFormat: 'dd-mm-yy'});
        $( "#search_to" ).datepicker({
            showOn: "button",
            buttonImage: "images/calendar.gif",
            buttonImageOnly: true,
            dateFormat: 'dd-mm-yy'});
    });   */
    
    $(function() {
        var dates = $( "#search_from, #search_to" ).datepicker({
            defaultDate: "0", 
            changeMonth: true,
            showOn: "button",
            buttonText: 'Scegli',
            showOn: 'both', 
            buttonImage: "http://www.belsalento.it/images/calendar.png",
            showAnim: 'blind',
            minDate: '0',
            buttonImageOnly: true,
            dateFormat: 'dd-mm-yy',
            dayNamesMin: ['Do', 'Lu', 'Ma', 'Me', 'Gi', 'Ve', 'Sa'],
            monthNamesShort: ['Gennaio','Febbraio','Marzo','Aprile','Maggio','Giugno','Luglio','Agosto','Settembre','Ottobre','Novenbre','Dicembre'], 
            onSelect: function( selectedDate ) {
                var option = this.id == "search_from" ? "minDate" : "maxDate",
                    instance = $( this ).data( "datepicker" );
                    date = $.datepicker.parseDate(
                        instance.settings.dateFormat ||
                        $.datepicker._defaults.dateFormat,
                        selectedDate, instance.settings );
                dates.not( this ).datepicker( "option", option, date );
            }
        });
        
        var datesp = $( "#check_in_pre, #check_out_pre" ).datepicker({
            defaultDate: "0",
            changeMonth: true,
            showOn: "button",
            buttonText: 'Scegli',
            showOn: 'both', 
            buttonImage: "http://www.belsalento.it/images/calendar.png",
            showAnim: 'blind',
            minDate: '0',
            buttonImageOnly: true,
            dateFormat: 'dd-mm-yy',
            dayNamesMin: ['Do', 'Lu', 'Ma', 'Me', 'Gi', 'Ve', 'Sa'],
            monthNamesShort: ['Gennaio','Febbraio','Marzo','Aprile','Maggio','Giugno','Luglio','Agosto','Settembre','Ottobre','Novenbre','Dicembre'], 
            onSelect: function( selectedDate ) {
                var option = this.id == "check_in_pre" ? "minDate" : "maxDate",
                    instance = $( this ).data( "datepicker" );
                    date = $.datepicker.parseDate(
                        instance.settings.dateFormat ||
                        $.datepicker._defaults.dateFormat,
                        selectedDate, instance.settings );
                datesp.not( this ).datepicker( "option", option, date );
            }
        });
    });
    
 $(document).ready(function(){ 
    $("#title_list_right").css("cursor","pointer").toggle(function(){  
       $(this).html("[Mostra]");  
     }, function () {  
      $(this).html("[Nascondi]");  
    });
    
    $("#title_list_right").click(function(){  
     $("#container_lista").toggle();  
    });  
}); 
    
     $.widget( "custom.catcomplete", $.ui.autocomplete, {
        _renderMenu: function( ul, items ) {
            var self = this,
                currentCategory = "";
            $.each( items, function( index, item ) {
                if ( item.category != currentCategory ) {
                    ul.append( "<li class='ui-autocomplete-category'>" + item.category + "</li>" );
                    currentCategory = item.category;
                }
                self._renderItem( ul, item );
            });
        }
    });

 
$(function() {
        $("#search_where").focus();
    
        $( "#search_where_hd" ).val('');
        
        $("#try_now").click(function() {
         $("#search_where").catcomplete("search");
        });
        
        $.ajax({
            url: "http://www.belsalento.it/options.xml",
            dataType: "xml",
            success: function( xmlResponse ) {
                var data = $( "input", xmlResponse ).map(function() {
                    return {
                        value: $( "text", this ).text(),
                        id: $( "value", this ).text(),
                        category: $( "tipo", this ).text(),
                        action: $( "search", this ).text(),
                        dourl: $( "do", this ).text(),
                        idurl: $( "seo_url", this ).text()
                    };
                }).get();
                $( "#search_where" ).catcomplete({
                    source: data,
                    minLength: 0,
                    selectFirst: true,
                    select: function( event, ui ) {
                       $("#search_where_hd" ).val(''+ ui.item.id +'');
                       //alert(ui.item.category);  
                       if(ui.item.category != 'Elenco Strutture'){
                         $("#go_search").attr('method', 'GET'); 
                         $("#go_search").attr('action', 'http://www.belsalento.it/searchlist.php');
                         $("#dosearch").attr('name','do');
                         $("#idsearch").attr('name','id');
                         $("#dosearch").val(''+ ui.item.dourl +'');
                         $("#idsearch").val(''+ ui.item.idurl +'');
                       }else{
                         $("#go_search").attr('action', 'http://www.belsalento.it/it/'+ ui.item.action +'');
                         $("#go_search").attr('method', 'POST');   
                         $("#dosearch").attr('name','nodo');
                         $("#idsearch").attr('name','noid');
                         $("#dosearch").val('');
                         $("#idsearch").val('');
                       }   
                      //  log( ui.item ?
                      //      "Selected: " + ui.item.value + ", geonameId: " + ui.item.id :
                      //      "Nothing selected, input was " + this.value );
                    },
                    focus: function(event, ui) {
                              try {
                              if(event.originalEvent.type != "menuselected") {
                               // Unset ID
                               $("#search_where_hd").val(""); 
                              }   
                             }
                             catch(err) { 
                              // unset ID 
                              $("#search_where_hd").val("");
                             }
                    }
                });
            }
        });

    $("#do_search").click(function(){
       var search = $("#search_where").val();
       var search_hd = $("#search_where_hd").val();
       var search_f = $("#search_from").val();
       var search_t = $("#search_to").val();
       var search_i = $("#search_indeciso").val();
       if(search_hd!=''){
        //alert($("#go_search").attr('action'));
     //   if(search_f == '' && search_t == ''){
      //    if($('#search_indeciso').attr('checked')){
      //     $("#go_search").submit();
      //    }else{
      //     $.jnotify("<b>Attenzione:</b> occorre inserire la data di check-in e di check-out", {
      //         type: "error",
      //         sticky: true,
      //         closeLabel: "&times Chiudi",
      //         showClose: true
      //     });     
      //    }  
     //   }else{
         $("#go_search").submit();     
     //   }
       }else{
        if(search!=''){
         $.jnotify("Nessun risultato per questa destinazione", {
             type: "error",
             sticky: true,
             closeLabel: "&times Chiudi",
             showClose: true
         }); 
        }else{
         $.jnotify("<b>Attenzione:</b> occorre selezionare una destinazione<br /> dal men&ugrave; a tendina per effettuare la ricerca", {
             type: "error",
             sticky: true,
             closeLabel: "&times Chiudi",
             showClose: true
         });  
        }
     //   $.jnotify("<b>Attenzione:</b> occorre selezionare una destinazione<br /> dal men&ugrave; a tendina per effettuare la ricerca", "error", true, "Chiudi messaggio");   
       }
    });
});
