/* Highlight submenu. */
if(v.modeType && v.modeType != 'undefined')
{
    if(config.requestType == 'GET')
    {
        if(v.modeType == 'in')
        {
            $('#mainNavbar li').removeClass('active').find("[href*='mode\\=" + v.modeType + "']").not('[href*=mode\\=invest]').parent().addClass('active');
        }
        else
        {
            $('#mainNavbar li').removeClass('active').find("[href*='mode\\=" + v.modeType + "']").parent().addClass('active');
        }
    }
    else
    {
        $('#mainNavbar li').removeClass('active');
        if(v.modeType == 'in' || v.modeType == 'all')
        {
            $('#mainNavbar li').find("[href*='trade-browse-" + v.modeType + ".html']").parent().addClass('active');
        }
        else
        {
            $('#mainNavbar li').find("[href*='-" + v.modeType + "']").parent().addClass('active');
        }
    }
}

$(document).ready(function()
{
    $.setAjaxForm('#tradeForm', function(response)
    {
        if(response.result == 'fail')
        {
            if(response.error && response.error.length)
            {
                $('#duplicateError').html($('.errorMessage').html());
                $('#duplicateError .alert').prepend(response.error).show();

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

    $('#menu a[href*=setReportUnit]').attr({'data-toggle' : 'modal', 'data-width' : 400});

    $('[name*=objectType]').change(function()
    {
        if($(this).prop('checked')) 
        {
            $('#allCustomer').change();
            $('#purchaseContract').empty().trigger('chosen:updated');
            $('[name*=objectType]').not(this).prop('checked', false).change();
            $('.traderTR').hide();
        }
        else
        {
            $('.traderTR').show();
            $('#contract').empty().trigger('chosen:updated').change();
            $('#trader').change();
        }

        $('#' + $(this).val()).parents('tr').toggle($(this).prop('checked'))
        if($(this).val() == 'order') $('.customerTR').toggle($(this).prop('checked'));
        if($(this).val() == 'contract') $('.allCustomerTR').toggle($(this).prop('checked'));
    })

    $('[name*=objectType]').each(function()
    {
        if($(this).prop('checked')) $(this).change();
    });

    /* Toggle create trader items. */
    $('[name*=createTrader]').change(function()
    {
        var $inputGroup = $(this).parents('.input-group');
        if($(this).prop('checked'))
        {
            $inputGroup.find('select').hide();
            $inputGroup.find('[id*=trader][id*=_chosen]').hide();
            $inputGroup.find('input[type=text][id*=traderName]').show().focus();
            $(this).parents('.input-group-addon').find('.icon-help-circle').hide();
        }
        else
        {
            $inputGroup.find('[id*=trader][id*=_chosen]').show();
            $inputGroup.find('input[type=text][id*=traderName]').hide();
        }
        $inputGroup.fixInputGroup();
    })

    $('[name*=createTrader]').change();

    $(document).on('change', '#customer,#trader', function()
    {
        if($(this).val())
        {
            $.get(createLink('trade', 'ajaxGetDepositor', 'customer=' + $(this).val()), function(depositor)
            {
                if(depositor)  $('tr.customer-depositor').show().find('#customerDepositor').val(depositor);
                if(!depositor) $('tr.customer-depositor').hide();
            });
        }
        else
        {
            $('tr.customer-depositor').hide();
        }
    })

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

/**
 * Get contract of a trader. 
 * 
 * @param  int    $traderID 
 * @param  string $type
 * @access public
 * @return void
 */
function getContract(traderID, type, selector)
{
    if(traderID == '' || traderID == '0') return false;

    var url = createLink('crm.contract', 'ajaxGetOptionMenu', 'traderID=' + traderID + '&contractID=&type=' + type);
    $(selector + ' select').empty().load(url, function()
    {
        $(selector + ' .chosen').trigger('chosen:updated');
        if(v.contract) $(selector + ' select').val(v.contract);
    });
}

/**
 * Get order of a customer. 
 * 
 * @param  int    $customerID 
 * @access public
 * @return void
 */
function getOrder(customerID)
{
    if(customerID == '') return false;
    $('.orderTD select').empty().load(createLink('crm.order', 'ajaxGetOptionMenu', 'customerID=' + customerID));
}

/**
 * Init table header
 * @access public
 * @return void
 */
function initTableHeader()
{
    $('.table-wrapper > table.table-fixed-head').each(function()
    {
        var $table = $(this);
        var $panel = $table.closest('.table-wrapper');

        if(!$table.length || !$table.children('thead').length) return;
        var isFixed = $panel.height() < $table.outerHeight();

        $panel.toggleClass('with-fixed-header', isFixed);
        var $header = $panel.children('.table-header-fixed').toggle(isFixed);
        if(!isFixed)
        {
            $table.find('thead').css('visibility', 'visible');
            return;
        }
        var tableWidth = $table.width();
        var $oldTableHead = $table.find('thead');
        var updateTh = function()
        {
            $header.find('thead').empty().append($oldTableHead.find('tr').clone());
        };
        if(!$header.length)
        {
            $header = $('<div class="table-header-fixed" style="position: absolute; left: 9px; top: 3px; right: 0; margin: 0 10px 0 0; background: #fff;"><table class="table table-fixed no-margin table-header-fixed-shadow"></table></div>').css('right', $panel.width() - tableWidth - 1);
            $oldTableHead.find('th').each(function(idx)
            {
                $(this).attr('data-idx', idx);
            });
            $header.find('.table').addClass($table.attr('class')).append($oldTableHead.css('visibility', 'hidden').clone().css('visibility', 'visible'));
            $panel.addClass('with-fixed-header').append($header);
        }
        else
        {
            updateTh();
        }

        var timeoutCall = null;
        $table.parent().off('scroll.initTableHeader').on('scroll.initTableHeader', function()
        {
            clearTimeout(timeoutCall);
            var $tableContainer = $(this);
            timeoutCall = setTimeout(function() {
                $panel.toggleClass('table-scrolled', $tableContainer.scrollTop() > 0);
            }, 200);
        });
    });
}
