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

$(document).ready(function()
{
    removeDitto();//Remove 'ditto' in first row.

    $('table.datatable').datatable({fixedHeader: true, fixedHeaderOffset: 44}).remove();

    var defaults = {chosenMode: true, disableEmptySearch: true, maxListCount: 0, searchDelay: 500}; // chosenMode: init picker as chosen and can update picker by trigger('chosen:updated').
    $('.datatable .select-picker').each(function()
    {
        $(this).find('option[value=ajax_search_more]').remove();

        var options = defaults;
        if($(this).data('url')) options = $.extend({remote: $(this).data('url')}, defaults);

        $(this).picker(options);
    });

    $('.datatable .form-date').fixedDate().datetimepicker(
    {
        language:  config.clientLang,
        weekStart: 1,
        todayBtn:  1,
        autoclose: 1,
        todayHighlight: 1,
        startView: 2,
        minView: 2,
        forceParse: 0,
        format: 'yyyy-mm-dd'
    });

    $('.datatable .type').change(function()
    {
        var index = $(this).parents('tr').data('index');
        var type  = $(this).val();
        var key   = $(this).data('key');
        var $tr   = $('.datatable .datatable-rows .flexarea table tr[data-index=' + index + ']');

        var $fakeDepositor = $('<input>').attr({id: 'fakeDepositor' + key, class: 'form-control', disabled: true});
        var $fakeCategory  = $('<input>').attr({id: 'fakeCategory'  + key, class: 'form-control', disabled: true});
        var $fakeTrader    = $('<input>').attr({id: 'fakeTrader'    + key, class: 'form-control', disabled: true});
        var $fakeProduct   = $('<input>').attr({id: 'fakeProduct'   + key, class: 'form-control', disabled: true});

        $tr.find('[id^=fakeDepositor], [id^=fakeCategory], [id^=fakeTrader], [id^=fakeProduct]').remove();

        if(type == 'fee') type = $(this).next('input:hidden').val();
        if(type == 'in' || type == 'out')
        {
            $tr.find('[name^=otherDepositor]').next('.picker').hide().after($fakeDepositor);
            $tr.find('[name^=category]').attr('disabled', true).next('.picker').hide();
            $tr.find('[name^=category].' + type).attr('disabled', false).next('.picker').show();
            $tr.find('[name^=trader]').parent().hide().attr('disabled', true).find('*').attr('disabled', true);
            $tr.find('[name^=trader]').parent('.' + type).show().attr('disabled', false).find('*').attr('disabled', false);
            $tr.find('[name^=product]').next('.picker').show();
        }
        if(type == 'transferin' || type == 'transferout')
        {
            $tr.find('[name^=otherDepositor]').next('.picker').show();
            $tr.find('[name^=category]').next('.picker').hide().parent().append($fakeCategory);
            $tr.find('[name^=trader]').parent().hide().parents('td').append($fakeTrader);
            $tr.find('[name^=product]').next('.picker').hide().after($fakeProduct);
        }
    })
    $('.datatable .type').change();

    $('.datatable [name*=createTrader]').each(function()
    {
        if($(this).prop('checked')) $(this).parents('.out').find('.picker').hide();
    })

    $('.datatable [name*=createCustomer]').each(function()
    {
        if($(this).prop('checked')) $(this).parents('.in').find('.picker').hide();
    })

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

    $('.datatable [name*=createCustomer]').change(function()
    {
        var $inputGroup = $(this).parents('.input-group');
        if($(this).prop('checked')) 
        {
            $inputGroup.find('select').hide();
            $inputGroup.find('.picker').hide();
            $inputGroup.find('input[type=text][id*=customerName]').show().focus();
            $(this).parents('.input-group-addon').find('.icon-help-circle').hide();
        }
        else
        {
            $inputGroup.find('.picker').show();
            $inputGroup.find('input[type=text][id*=customerName]').hide();
        }
        $inputGroup.fixInputGroup();
    })

    $('.datatable .toggleHide').click(function()
    {
        if($(this).hasClass('showed'))
        {
            $(this).attr('title', v.showExistTrade);
        }
        else
        {
            $(this).attr('title', v.hideExistTrade);
        }
        $(this).toggleClass('showed');
        $(this).find('i').toggleClass('icon-plus icon-minus');
        $('.datatable .existTrades' + $(this).data('key')).toggle();
        $('.datatable .similarTrades' + $(this).data('key')).toggle();
    });

    $('.datatable .hasViewLink td:not(.hasCheckbox)').click(function()
    {
        var url = $(this).parents('tr').find('[name^=viewLink]').val();
        if(url) window.open(url);

        return false;
    });

    $('.picker-selection-text').bind('DOMNodeInserted',function()
    {
        $(this).closest('.picker-selections').attr('title', $(this).text());
    });

    $('.datatable [name^=product]').change(function()
    {
        var $tr   = $(this).closest('tr');
        var index = $tr.data('index');
        var type  = $('.datatable .datatable-rows .fixed-left table tr[data-index=' + index + '] [name^=type]').val();
        if(type != 'in') return false;

        var product = $(this).val();
        if(product == '0') return false;
        $.get(createLink('product', 'ajaxGetSubject', 'product=' + product), function(category)
        {
            if(category && category != '0') $tr.find('[name^=category]').val(category).trigger('chosen:updated');
        });
    })

    $(window).scroll(function()
    {
        fixScrollWrapper();
    }).resize(function()
    {
        fixScrollWrapper();
    });

    if($('.loading-box').length > 0) $('.loading-box').hide();
    $('#ajaxForm').removeClass('hide');
    $('.input-group').fixInputGroup();
    fixScrollWrapper();
});

function fixScrollWrapper()
{
    var tbHeight   = $(document).height();
    var wHeight    = $(window).height();
    var wScrollTop = $(window).scrollTop();
    var marginBtm  = parseInt($('div.datatable').parents('.panel').css('margin-bottom'));
    var paddingBtm = parseInt($('div.datatable').parent('.panel-body').css('padding-bottom'));
    var fHeight    = $('div.table-footer').outerHeight();

    if(tbHeight - wScrollTop - wHeight - marginBtm - paddingBtm - fHeight > 0)
    {
        $('div.datatable > div.scroll-wrapper').css('bottom', tbHeight - wHeight - wScrollTop - marginBtm - paddingBtm - fHeight);
        $('div.datatable > div.scroll-wrapper .bar').css('height', '15px');
    }
    else
    {
        $('div.datatable > div.scroll-wrapper').css('bottom', 0);
        $('div.datatable > div.scroll-wrapper .bar').css('height', '10px');
    }
}
