$(document).ready(function(){
    var throttling = 300; //Time in milliseconds to wait before sending a request for autocomplete
    var topOffset = 18;
    var leftOffset = -3;
    var throttlingTimeout = null;

    $('form.quote-form').attr('autocomplete', 'off');

    $('form.quote-form').submit(function(){
        if ($('#origin_id').val() == ''){
            alert ('Please select a Starting Airport from the list of suggestions');
            return false;
        }

        if ($('#destination_id').val() == ''){
            alert ('Please select a Finishing Airport from the list of suggestions');
            return false;
        }
        return true;
    });

    $('#origin, #destination').keyup(function(keyup_event){
        if (keyup_event.keyCode == 13){//return
            clearTimeout(throttlingTimeout);
            return false;
        }

        if ($('#auto_hover').size() > 0){//autocomplete open
            if (keyup_event.keyCode == 9){//tab
                clearTimeout(throttlingTimeout);
                return false;
            }
            if (keyup_event.keyCode == 27){//escape
                $('#auto_hover').remove();
            }else if (keyup_event.keyCode == 38){//up arrow
                if ($('#auto_hover li.hover').size()){
                    $('#auto_hover li.hover').prev('li').addClass('hover').next().removeClass('hover');
                }
                clearTimeout(throttlingTimeout);
                return false;
            }else if (keyup_event.keyCode == 40){//down arrow
                if ($('#auto_hover li.hover').size()){
                    $('#auto_hover li.hover').next('li').addClass('hover').prev().removeClass('hover');
                }else{
                    $('#auto_hover li:first').addClass('hover');
                }
                clearTimeout(throttlingTimeout);
                return false;
            }
        }
        clearTimeout(throttlingTimeout);

        //Reset value
        if ($('#' + $(this).attr('id') + '_id').val() != ''){
            $('#' + $(this).attr('id') + '_id').val('');
            $(this).val('');
        }

        var func_ref = fetch_autocomplete($(this));
        throttlingTimeout = setTimeout(func_ref, throttling);
    }).keydown(function(keydown_event){
        if ($('#auto_hover').size() > 0){//autocomplete open
            if (keydown_event.keyCode == 13){//return
                set_autocomplete($(this));
                clearTimeout(throttlingTimeout);
                keydown_event.preventDefault();
                return false;
            }
        }
    }).blur(function(){
        set_autocomplete($(this));
    });

    function fetch_autocomplete(jquery_selector){
        return (function(){
            throttlingTimeout = null;
            if (jquery_selector.val() === ''){
                return;
            }
            $.post(JETSUITE.ajax_url, { 'action': 'fetch_airports', 'val': jquery_selector.val() },
            function(data, textStatus){
                $('#auto_hover').remove();
                if (data.length <= 0){
                    return;
                }
                var position = jquery_selector.offset();
                //build hover div
                var hover = $('<div id="auto_hover"><div class="top_arrow">&nbsp;</div><ul></ul></div>');
                //append results
                for (var key in data){
                    $('<li>' + data[key]['name'] + '</li>').data('airport_id', data[key]['id']).appendTo(hover.find('ul'));
                }
                position.top = (position.top + (jquery_selector.height())) + topOffset;
                hover.css('left', position.left).css('top', position.top);
                $('body').append(hover);
                hover = $('#auto_hover');
                hover.css('left', (position.left + (jquery_selector.width() / 2)) - (hover.width() / 2) + leftOffset);
                hover.find('li').hover(function(){
                    $(this).siblings('li').removeClass('hover');
                    $(this).addClass('hover');
                }, function(){
                    $(this).removeClass('hover');
                });
            }, "json");
        })
    }

    function set_autocomplete(jquery_selector){
        if($('#auto_hover li.hover').size()){
            $('#' + jquery_selector.attr('id') + '_id').val($('#auto_hover li.hover').data('airport_id'));
            var text = $('#auto_hover li.hover').text();
            $('#auto_hover').remove();
            jquery_selector.val(text);
        }
    }
});