$(document).ready(function() {
    var timer;
    var selecting = false;
    $('[name=search]').keyup(function() {
        $('#search-choices').hide();
        clearTimeout(timer);
        var search = $(this).val();
        if (search.length >= 3) {
           $('#search-choices table').html('');
           timer = setTimeout(function() {
               $.ajax({
                   url: '/welcome/ajax_search/' + search + '/5',
                   dataType: 'json',
                   success: function(data) {
                       clearTimeout(timer);
                       if (data.success) {
                           if (data.events.length > 0) {
                               $('#search-choices table').append('<tr><th>Events</th></tr>');
                               $.each(data.events, function(i, event) {
                                    $('#search-choices table').append('<tr><td><a href="/event/' + event.display_id + '">' + event.display_title + '<div style="color: #666;">' + event.start_datetime + '</div><div style="color: #666;">' + event.venue_name + ', ' + event.city + '</div></a></td></tr>');
                               });
                           }
                           if (data.tours.length > 0) {
                               $('#search-choices table').append('<tr><th>Tours</th></tr>');
                               $.each(data.tours, function(i, tour) {
                                    $('#search-choices table').append('<tr><td><a href="/tour/' + tour.tour_id + '">' + tour.name + '<div style="color: #666;">' + tour.start_date + ' - ' + tour.end_date + '</div></a></td></tr>');
                               });
                           }
                           if (data.venues.length > 0) {
                               $('#search-choices table').append('<tr><th>Venues</th></tr>');
                               $.each(data.venues, function(i, venue) {
                                    $('#search-choices table').append('<tr><td><a href="/venue/' + venue.venue_id + '">' + venue.name + '</a></td></tr>');
                               });
                           }
                           $('#search-choices table').append('<tr><td align="right" class="all"><strong><a href="/search/?search=' + search + '">See all results for \'' + search + '\'</a></strong></td></tr>');
                           $('#search-choices').slideDown(400);
                       } else {
                           $('#search-choices').hide();
                       }
                   }
               });
           }, 330);
       } else {
            $('#search-choices').hide();
       }
    }).blur(function() {
        if(!selecting) {
            $('#search-choices').hide();
        }
    });

    $('#search-choices').mouseover(function() {
       selecting = true;
    });

    $('#search-choices').mouseout(function() {
       selecting = false;
    });
});


