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

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

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

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

    $(document).on('hide.zui.modal', '#ajaxModal', 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;

        $('#customer').change();
    });

    $('#customer').change(function()
    {
        var customerID = $(this).val();

        $('#money').val('');
        $('#invoiceTitle').val('');
        $('#taxNumber').val('');
        $('#registedAddress').val('');
        $('#phone').val('');
        $('#bankName').val('');
        $('#bankAccount').val('');

        getContracts(customerID);
        getCustomerInvoices(customerID);

        $('#hasTrade').change();
    })

    $('#contract').change(function()
    {
        if(!$.isNumeric($(this).val())) return false;

        $('#money').val('');

        $('#detailBox').load(createLink('invoice', 'ajaxGetInvoiceDetails', 'contractID=' + $(this).val()), function()
        {
            $(this).find("select").chosen({no_results_text: v.noResultsMatch, disable_search_threshold: 1, search_contains: true, width: '100%', allow_single_deselect: true});
            $('[name^=priceList]').change();
            $('select[name^=itemList]').change();
        });

        $.get(createLink('invoice', 'ajaxGetDrawnMoney', "contractID=" + $(this).val()), function(drawnMoney)
        {
            if(drawnMoney == '') drawnMoney = 0;
            if(!$.isNumeric(drawnMoney)) return false;

            drawnMoney = Math.round(drawnMoney * 100) / 100;
            if(drawnMoney == 0) drawnMoney = '';
            $('#drawnMoney').val(drawnMoney);
        });

        $('#hasTrade').change();
    });

    $('#type').change(function()
    {
        $('#phone, #bankName').parents('tr').find('.required').toggle($(this).val() == 'companySpecial');
    });

    $('#customerInvoice').change(function()
    {
        getCustomerInvoice($(this).val());
    });

    $('#hasTrade').change(function()
    {
        if($(this).prop('checked'))
        {
            var customer = $('#customer').val() ? $('#customer').val() : 0;
            var contract = $('#contract').val() ? $('#contract').val() : 0;
            var link = createLink('invoice', 'ajaxGetRelatedTrades', 'invoiceID=0&customer=' + customer + '&contract=' + contract);
            $('[name^=trades]').load(link, function()
            {
                $('[name^=trades]').trigger('chosen:updated');
            });

            $('.tradesTR').show();
        }
        else
        {
            $('.tradesTR').hide();
        }
    });

    $('#type').change();
    $('#customer').change();
})

function getContracts(customerID)
{
    if(!customerID) return false;

    $('.contractTD select').empty().load(createLink('crm.contract', 'ajaxGetOptionMenu', 'customerID=' + customerID + '&current=' + v.contractID), function()
    {
        if(v.contractID) $('#contract').val(v.contractID).change();
    });
}

function getCustomerInvoices(customerID)
{
    if(!customerID) return false;

    $.getJSON(createLink('customer', 'ajaxGetCustomerInvoices', 'id=' + customerID), function(customerInvoices)
    {
        var count = 0;
        for(var i in customerInvoices) count++;
        if(count > 0)
        {
            $('.customerTD').removeAttr('colspan');
            $('.invoiceTD').show();

            $('#customerInvoice').empty();
            var index = 0;
            for(var i in customerInvoices)
            {
                var customerInvoice = customerInvoices[i];
                var selected        = '';

                if(index == 0) 
                {
                    updateInvoiceInfo(customerInvoice);
                    selected = 'selected';
                }

                $('#customerInvoice').append("<option value='" + customerInvoice.id + "'" + selected + '>' + customerInvoice.invoiceTitle + '</option>');

                index++;
            }
        }
        else
        {
            $('.customerTD').attr('colspan', '3');
            $('.invoiceTD').hide();
        }
    });

    $('.copyCustomer').click(function()
    {
        $(this).parents('tr').find('#invoiceTitle').val($('#customer option:selected').text());
    })
}

function getCustomerInvoice(customerInvoiceID)
{
    if(!customerInvoiceID) return false;
    
    $.getJSON(createLink('customer', 'ajaxGetCustomerInvoices', 'id=' + $('#customer').val() + '&customerInvoiceID=' + customerInvoiceID), function(customerInvoice)
    {
        if(typeof customerInvoice == 'object')
        {
            updateInvoiceInfo(customerInvoice);
        }
    });
}

function updateInvoiceInfo(customerInvoice)
{
    $('#invoiceTitle').val(customerInvoice.invoiceTitle);
    $('#taxNumber').val(customerInvoice.taxNumber);
    $('#registedAddress').val(customerInvoice.registedAddress);
    $('#phone').val(customerInvoice.phone);
    $('#bankName').val(customerInvoice.bankName);
    $('#bankAccount').val(customerInvoice.bankAccount);
}
