var $selectedItem;
var selectItem = function(item)
{
    $selectedItem = $(item).first();
    $('#searchModal').modal('hide');
};

$(document).ready(function()
{
    var showSearchModal = function()
    {
        var key      = $('#customer_chosen .chosen-results > li.no-results > span').text();
        var relation = 'client'
        var link     = createLink('customer', 'ajaxSearchCustomer', 'key=' + key + '&relation=' + relation);
        $.zui.modalTrigger.show({name: 'searchModal', url: link, backdrop: 'static'});
    };

    $(document).on('change', '#customer', function()
    {
        if($(this).val() === 'ajax_search_more')
        {
             showSearchModal();
        }
    });

    $(document).on('click', '#customer_chosen .chosen-results > li.no-results', showSearchModal);

    $(document).on('hide.zui.modal', '#searchModal', function()
    {
        var key       = '';
        var $customer = $('#customer');
        if($selectedItem && $selectedItem.length)
        {
            key = $selectedItem.data('key');
            if(!$customer.children('option[value="' + key + '"]').length)
            {
                $customer.prepend('<option value="' + key + '">' + $selectedItem.text() + '</option>');
            }
        }
        $customer.val(key).trigger("chosen:updated");
        $selectedItem = null;
    });
})
