var $selectedItem;
var selectItem = function(item)
{
    $selectedItem = $(item).first();
    var modal = $('#ajaxModal');
    var link  = createLink(config.currentModule, 'create', 'traderID=' + $selectedItem.data('key'));
    modal.load(link, function(){$(this).find('.modal-dialog').css('width', $(this).data('width')); $.zui.ajustModalPosition()})
};

$(document).ready(function()
{
    var showSearchModal = function()
    {
        var key      = $('#ajaxModal #trader_chosen .chosen-results > li.no-results > span').text();
        var relation = 'client';
        var link     = createLink('customer', 'ajaxSearchCustomer', 'key=' + key + '&relation=' + relation);
        $('#ajaxModal').load(link);
    };

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

    var $table  = $('#receivableTable');
    var $trader = $table.find('#trader');
    var $origin = $table.find('#origin');

    $.setAjaxForm('#createForm', function(response)
    {
        if(response.result == 'fail')
        {
            if(response.error && response.error.length)
            {
                var $error = $table.find('#duplicateError');

                $error.html($('.errorMessage').html());
                $error.find('.alert').prepend(response.error).show();

                $(document).on('click', '#receivableTable #duplicateError #continueSubmit', function()
                {
                    $table.find('#submit').attr('type', 'button');
                    $error.append("<input value='1' name='continue' class='hide'>");
                })
            }
        }
        else
        {
            setTimeout(function(){location.href = response.locate;}, 1200);
        }
    });

    $trader.change(function()
    {
        if($(this).val() === 'showmore')
        {
            showSearchModal();
            return false;
        }

        if($(this).val() != 0) $origin.change();
    });

    $table.find('#createTrader').click(function()
    {
        $(this).parents('td').find('.required').hide();

        var $traderChosen = $table.find('#trader_chosen');
        var $newTrader    = $table.find('#newTrader');
        var $traderInfo   = $table.find('.traderInfo');

        if($(this).prop('checked')) 
        {
            $trader.hide();
            $traderChosen.hide();
            $newTrader.show().focus();
            $traderInfo.show();
        }
        else
        {
            $traderChosen.show();
            $newTrader.hide();
            $traderInfo.hide();
        }
    });

    $origin.change();
})
