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

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

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

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

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