$(function () {
    $('input.datetime').datetimepicker({
        format: 'dd-mm-yyyy hh:ii'
    });

    $('.confirm-application').click(function () {
        if ($(this).attr('disabled')) {
            return;
        }

        var $that = $(this);
        var url = $('[data-confirm-url]').data('confirm-url');
        var id = $(this).closest('tr').data('id');

        $.post(url, {id: id}, function (response) {
            if (response === true) {
                $that.attr('checked', 'checked').attr('disabled', 'disabled');
            }
        });
    });

    var textareaTimeout;

    $('.application-comment').change(function () {
        saveComment(this);
    }).keyup(function () {
        var textarea = this;
        clearTimeout(textareaTimeout);

        textareaTimeout = setTimeout(function() {
            saveComment(textarea);
        }, 800);
    });

    function saveComment(textarea) {
        var $textarea = $(textarea);
        var url = $('[data-confirm-url]').data('comment-url');
        var id = $textarea.closest('tr').data('id');

        $.post(url, {id: id, comment: $textarea.val()}, function (response) {
            if (response === true) {

            }
        });
    }

    var $createApplication = $('#create-application');
    if($createApplication.length) {
        var connections,
            $applicationLoading = $('#application_loading'),
            $applicationUnloading = $('#application_unloading'),
            $applicationVolume = $('#application_volume'),
            $applicationWeight = $('#application_weight'),
            $costValue = $('#cost-value'),
            unloadingsClone = $applicationUnloading.clone(),
            connectionsUrl = $createApplication.data('connections-url'),
            $documentary = $('#application_documentary'),
            $thc = $('#application_thc'),
            $warehouse = $('#application_warehouse'),
            $isps = $('#application_isps'),
            $customs = $('#application_customs');

        // get all possible connections
        $.get(connectionsUrl, function (response) {
            connections = response;
            updateUnloadingsPorts();
            checkPoland();
        });

        // remove unused unloading for selected loading
        function updateUnloadingsPorts() {
            var loadingId = $applicationLoading.val(),
                unloadingId = $applicationUnloading.val(),
                unloadingsToLeft = unloadingsClone.clone(),
                unloadings = [];

            if (!loadingId) {
                return;
            }

            // find used unloadings
            $.each(connections, function () {
                if (this.l == loadingId) {
                    unloadings.push(this.u);
                }
            });

            // remove unused unloadings
            $.each(unloadingsToLeft.find('option'), function () {
                if ($(this).val() && unloadings.indexOf(parseInt($(this).val())) < 0) {
                    $(this).remove();
                }
            });

            // remove empty optgroup
            $.each(unloadingsToLeft.find('optgroup'), function () {
                if (!$(this).find('option').length) {
                    $(this).remove();
                }
            });

            // set clone html to select field
            $applicationUnloading.html(unloadingsToLeft.html());
            $applicationUnloading.trigger('chosen:updated');

            if (unloadingId) {
                $applicationUnloading.val(unloadingId);
                $applicationUnloading.trigger('chosen:updated');
            }

            updateCost();
        }

        $applicationLoading.change(function () {
            updateUnloadingsPorts();

            checkPoland();
        });

        function checkPoland() {
            var city = $applicationLoading.val() || 'a';
            var country = $applicationLoading.find('[value=' + city + ']').parent().attr('label');
            if(country == 'Polska') {
                $createApplication.addClass('polska');
                $('.transport').hide().find('input').val('');
                $('#application_transport').prop('checked', false);
                $thc.prop('checked', false);
                $isps.prop('checked', false);
            } else {
                $createApplication.removeClass('polska');
                $warehouse.prop('checked', false);
            }
        }

        $applicationUnloading.change(function () {
            updateCost();
        });

        $applicationVolume.keyup(function () {
            updateCost();
        });

        $applicationWeight.keyup(function () {
            updateCost();
        });

        $documentary.change(function () {
            updateCost();
        });

        $warehouse.change(function () {
            updateCost();
        });

        $thc.change(function () {
            updateCost();
        });

        $isps.change(function () {
            updateCost();
        });

        $customs.change(function () {
            updateCost();
        });

        function updateCost() {
            var cost = 0;
            $.each(connections, function () {
                if (this.l == $applicationLoading.val() && this.u == $applicationUnloading.val()) {
                    cost = this.c;
                }
            });

            var volume = $applicationVolume.val();
            var weight = $applicationWeight.val();

            volume = parseFloat(volume.replace(',', '.'));
            weight = parseFloat(weight) / 1000;

            if (!$applicationLoading.val() || !$applicationUnloading.val() || !volume || !weight) {
                $costValue.html('0');
                return;
            }

            var valueWeight = volume > weight ? volume : weight;

            cost = cost * valueWeight;


            if($documentary.prop('checked')) {
                cost += parseFloat($documentary.data('cost'));
            }

            if($thc.prop('checked')) {
                cost += parseFloat($thc.data('cost')) * valueWeight;
            }

            if($warehouse.prop('checked')) {
                cost += parseFloat($thc.data('cost')) * valueWeight;
            }

            if($isps.prop('checked')) {
                cost += parseFloat($isps.data('cost')) * weight;
            }

            if($customs.prop('checked')) {
                cost += parseFloat($customs.data('cost'));
            }

            if (volume <= 1 && weight <= 1) {
                $costValue.html(cost);
                return;
            }

            $costValue.html(Math.floor(cost));
        }
    }

    $('#application_transport').change(function () {
        var $transport = $('.transport');
        $transport.slideToggle();

        if(!$(this).prop('checked')) {
            $transport.find('input').val('');
        }
    });
});