$(function()
{
    $('#type').css('width', $('#sn').css('width'));

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

    $('#type').change(function()
    {
        $('.paper').toggle($(this).val() != 'companyDigitalOrdinary');
        $('.digital').toggle($(this).val() == 'companyDigitalOrdinary');
    });

    $('#status').change(function()
    {
        $('#contact, #express, #waybill, #address, #sendway, #sendAccount').prev('.required').remove();
        if($(this).val() != 'wait')
        {
            if($('#expressedBy').val() != '' || $('#expressedDate').val() != '')
            {
                var requiredFields = '#contact,#sendway';

                if($('#expressedBy').val() != '')   requiredFields += ',#expressedDate';
                if($('#expressedDate').val() != '') requiredFields += ',#expressedBy';
                if($('#type').val() != 'companyDigitalOrdinary') requiredFields += ',#express,#waybill,#address';
                if($('#type').val() == 'companyDigitalOrdinary') requiredFields += ',#sendAccount';

                $(requiredFields).before("<div class='required required-wrapper'></div>");
            }
        }
        $('#sn, #contact, #express, #waybill, #address, #sendway, #sendAccount').css('border-color', '').parents('td').find('.text-error').remove();
    });

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

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

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