$( document ).ready(function() {

    $( function() {
        var locale = $("#locale").val();
        $( "#search-all" ).autocomplete({
            minLength: 2,
            delay: 500,
            classes: {
                "ui-autocomplete": "highlight"
            },
            source: function( request, response ) {

                $.getJSON( "/api/v1/search-all?locale="+locale, request, function( data, status, xhr ) {
                    response( data );
                });
            },

            select: function( event, ui ) {
                //Handle both country and indicator search
                var countryCode = $("#countryCode").val();
                var countryId = $("#countryId").val();
                var countryText = $("#countryText").val();

                if(ui.item.SearchType == 'Indicator'){
                    var redirect_url = '/ind/'+countryCode+'?ind='+ui.item.Id+'&dim='+ui.item.dim+'&dom=' +
                        ui.item.dimTitle+'&cc='+countryCode+'&ci='+countryId+'&cn='+countryText;
                    window.location = redirect_url;
                }
                else if(ui.item.SearchType == 'Country'){
                    var redirect_url = '/'+ui.item.Id.toLowerCase();
                    window.location = redirect_url;
                }
            }
        });
    });

    $( function() {
        var locale = $("#locale").val();
        $( ".indicators-search" ).autocomplete({
          minLength: 2,
          delay: 500,
          source: function( request, response ) {

            $.getJSON( "/api/v1/indicators?locale="+locale, request, function( data, status, xhr ) {
                response( data );
            });
          },
          select: function( event, ui ) {
              $("#indid").val(ui.item.Id);
          }
        });
    });

    //Handles resizing of the nav bar menus
    $('#monitor').html($(window).width());
    $(window).resize(function() {
        var viewportWidth = $(window).width();
        $('#monitor').html(viewportWidth);
    });
});

