function initializeCustTariffs() {
    $("#Keywords").attr('placeholder', $('#searchPlaceholder').val());

    $dataTable = $('#mainGrid');
    $dataTable.DataTable({
        ajax: {
            url: $dataTable.attr('data-url'),
            data: function (d) {
                d.Keywords = $("#Keywords").val();
            }
        },
        columns: [
            { data: "Disabled", name: "AcDisabled", render: $.fn.dataTable.render.toggle(false, true), className: 'dt-body-center' },
            { data: "CustTariff", name: "AcCustTarif", filtertype: "text", render: $.fn.dataTable.render.link("CustTariff") },
            { data: "Name", name: "AcName", filtertype: "text", render: $.fn.dataTable.render.link("CustTariff") },
            { data: "Rate", name: "AnRate", filtertype: "number" },
            { data: "Unit", name: "AcUM", filtertype: "text" }
        ]
    });

    $("select").off("change.tableReload");
    $("select").on("change.tableReload", function () {
        $.fn.dataTable.reload($dataTable);
    });

    var typingTimer;
    var doneTypingInterval = 600;
    $('#Keywords').off('keyup');
    $('#Keywords').on('keyup', function () {
        clearTimeout(typingTimer);
        typingTimer = setTimeout(function () { $.fn.dataTable.reload($dataTable); }, doneTypingInterval);
    });
}

function initializeCustTariffsEdit() {
    var tariffItems = [];
    var selectedItemData;

    $('.input-validation-error').parents('.form-group').addClass('has-error');
    $('.field-validation-error').addClass('text-danger');

    var elems = Array.prototype.slice.call(document.querySelectorAll('.js-switch'));
    elems.forEach(function (html) {
        var switchery = new Switchery(html, { size: 'small' });
    });

    loadItems();

    initializeExciseTypeahead($('#DutySearch').attr('dataUrl'), $('#DutySearch'), $('#DutySearch'), function (item) {
        $("#DutySearch").val(item.id);
        selectedItemData = item;
        return { selected: true, value: item.id };
    });

    function loadItems() {
        if (!$("#CustTariff").val())
            return;

        swapLoadingIcon(true, "add-excise");
        $.post($("#CustTariffItemsUrl").val() + '?id=' + $("#CustTariff").val(), function (data) {
            for (var i = 0; i < data.length; i++) {
                tariffItems.push(data[i]);
                appendIdentToTable(data[i]);
            }

            swapLoadingIcon(false, "add-excise");
        }, "json");
    }

    $("#DutySearch").on('keydown', function (e) {
        if (e.keyCode === 13) {
            e.preventDefault();
            addPosition();
        }
    });

    $('#add-excise').on('click', function () {
        addPosition();
    });

    function addPosition() {
        if (selectedItemData) {

            if ($("#IsEdit").val() === "False") {
                confirm();
            } else {
                swapLoadingIcon(true, "add-excise");

                $.post($("#CreateCustTariffItemUrl").val(), {
                    CustTariff: $("#CustTariff").val(),
                    SetOfTax: selectedItemData.id,
                    Quantity: 1,
                    ExcisePercent: 0,
                    DateFrom: new Date(),
                    ExciseValue: 0,
                    Unit: $("#Unit option:selected").val(),
                    Rate: 1,
                    Currency: $("#Currency").val()
                }).done(function (response) {
                    if (response.success) {
                        tariffItems.push(response.item);
                        appendIdentToTable(response.item);
                    }

                    swapLoadingIcon(false, "add-excise");
                });
            }
        }
    }

    removeItem = function (anQid) {
        swal({
            title: '',
            text: $("#RemoveItemMsg").val(),
            type: "warning",
            showCancelButton: true,
            confirmButtonColor: "#DD6B55",
            confirmButtonText: $("#YesLoc").val(),
            cancelButtonText: $("#NoLoc").val(),
            closeOnConfirm: true
        }, function () {
            swapLoadingIcon(true, "add-excise");
            $.post($("#RemoveItemUrl").val(), { qid: anQid })
                .done(function (response) {
                    tariffItems.splice(getItemIndex(anQid), 1);
                    $("#position-" + anQid).remove();

                    swapLoadingIcon(false, "add-excise");
                });
        });
    };

    savePosition = function (anQid) {
        swapLoadingIcon(true, "save-" + anQid);
        $.post($("#UpdateItemUrl").val(), getItemData(anQid))
            .done(function (response) {
                swapLoadingIcon(false, "save-" + anQid);
            });
    };

    function appendIdentToTable(data) {
        createIdentTableRow($("#idents"), data, $("#DefaultDecimalPlacesPrice").val(), $("#DefaultDecimalPlacesQuantity").val(), $("#DefaultDecimalPlacesValue").val());
        initializeNumberInputs();
    }

    function createIdentTableRow($element, data, decimalPlacesPrice, decimalPlacesQuntity, decimalPlacesValue) {
        var $row = $('<tr role="row" id="position-' + data.AnQid + '"></tr>');
        $row.append('<td><input id="setOfTax-' + data.AnQid + '" type="text"  value="' + data.SetOfTax + '" class="form-control" readonly /></td>');
        $row.append('<td><select id="type-' + data.AnQid + '" value="' + data.Type + '" class="form-control" disabled>' + $("#tariffType").html() + '</select></td>');

        $row.append('<td><input id="dateFrom-' + data.AnQid + '" type="text" value="' + parseJsonDate(data.DateFrom) + '" class="form-control datepicker invoice-input editableInput required" autocomplete="off" /></td>');
        $row.append('<td><input id="dateTo-' + data.AnQid + '" type="text" value="' + parseJsonDate(data.DateTo) + '" class="form-control datepicker invoice-input editableInput" autocomplete="off" /></td>');

        $row.append('<td><input id="percent-' + data.AnQid + '" type="text" value="' + data.ExcisePercent + '" step="' + decimalPlacesPrice + '" class="form-control numberInput invoice-input editableInput text-right required" autocomplete="off" /></td>');
        $row.append('<td><select id="base-' + data.AnQid + '" value="' + data.BaseType + '" class="form-control">' + $("#baseOptions").html() + '</select></td>');

        $row.append('<td><input id="value-' + data.AnQid + '" type="text" value="' + data.ExciseValue + '" step="' + decimalPlacesValue + '" class="form-control numberInput invoice-input editableInput text-right required" autocomplete="off" /></td>');
        $row.append('<td><input id="quantity-' + data.AnQid + '" type="text" value="' + data.Quantity + '" step="' + decimalPlacesQuntity + '" class="form-control numberInput invoice-input editableInput text-right required" autocomplete="off" /></td>');
        $row.append('<td><select id="unit-' + data.AnQid + '" value="' + data.Unit + '" class="form-control">' + $("#measUnitOptions").html() + '</select></td>');
        $row.append('<td><input id="converter-' + data.AnQid + '" type="text" value="' + data.Rate + '" step="' + decimalPlacesPrice + '" class="form-control numberInput invoice-input editableInput text-right required" autocomplete="off" /></td>');

        $row.append('<td><select id="currency-' + data.AnQid + '" value="' + data.Currency + '" class="form-control">' + $("#currencyOptions").html() + '</select></td>');

        $row.append('<td><button type="button" class="btn btn-success" id="save-' + data.AnQid + '" onclick="savePosition(' + data.AnQid + ')"><i class="fa fa-check"></i></button>' +
            '<button type="button" class="btn btn-danger" id="remove-' + data.AnQid + '" onclick="removeItem(' + data.AnQid + ')"><i class="fa fa-times"></i></button></td>');

        $element.append($row);
        $('#unit-' + data.AnQid).val(data.Unit);
        $('#type-' + data.AnQid).val(data.Type);
        $('#base-' + data.AnQid).val(data.BaseType);
        $('#currency-' + data.AnQid).val(data.Currency);

        $('.datepicker').datepicker()
            .on('click', function (e) {
                $(this).select();
            }).on('changeDate', function () {
                $(this).datepicker('hide');
            });

        selectedItemData = null;
    }

    function swapLoadingIcon(loading, buttonId) {
        var buttonIcon;
        if (buttonId === "saveButton") {
            buttonIcon = "fa fa-save";
        }
        else {
            buttonIcon = "fa fa-plus";
        }

        if (loading) {
            $("#" + buttonId + "-icon").removeClass(buttonIcon);
            $("#" + buttonId + "-icon").addClass("fa fa-spinner fa-spin fa-fw");
            $("#" + buttonId).attr("disabled", true);
        }
        else {
            $("#" + buttonId + "-icon").removeClass("fa fa-spinner fa-spin fa-fw");
            $("#" + buttonId + "-icon").addClass(buttonIcon);
            $("#" + buttonId).removeAttr("disabled");
        }
    }

    function getItemIndex(anQid) {
        for (var i = 0; i < tariffItems.length; i++) {
            if (tariffItems[i].AnQid === anQid) {
                return tariffItems.indexOf(tariffItems[i]);
            }
        }
    }

    function getItemData(anQid) {
        var item = {
            AnQid: anQid,
            CustTariff: $("#CustTariff").val(),
            SetOfTax: $("#setOfTax-" + anQid).val(),
            Quantity: formatDisplay($("#DefaultDecimalPlacesQuantity").val(), $("#quantity-" + anQid).val(), true),
            ExcisePercent: formatDisplay($("#DefaultDecimalPlacesPrice").val(), $("#percent-" + anQid).val(), true),
            ExciseValue: formatDisplay($("#DefaultDecimalPlacesValue").val(), $("#value-" + anQid).val(), true),
            DateFrom: $("#dateFrom-" + anQid).val(),
            DateTo: $("#dateTo-" + anQid).val(),
            Unit: $("#unit-" + anQid + " option:selected").val(),
            Rate: formatDisplay($("#DefaultDecimalPlacesPrice").val(), $("#converter-" + anQid).val(), true),
            Currency: $("#currency-" + anQid).val(),
            BaseType: $("#base-" + anQid).val()
        };

        tariffItems[getItemIndex(anQid)] = item;
        return item;
    }

    confirm = function () {
        swapLoadingIcon(true, "saveButton");

        var formData = $("#CustTariffForm").serializeArray();

        var url;
        if ($("#IsEdit").val() === "True") {
            url = $("#UpdateCustTariffUrl").val();
        } else {
            url = $("#CreateCustTariffUrl").val();
        }

        $.post(url, formData)
            .done(function (response) {
                if (response.Success) {
                    if ($("#IsEdit").val() === "False") {
                        $("#IsEdit").val("True");
                        window.history.pushState({}, null, $("#UpdateCustTariffUrl").val() + "?id=" + response.data.CustTariff);
                        clearValidationErrors();
                    }

                    displayErrors(response);
                    addPosition();
                } else {
                    displayErrors(response);

                    if (response.errors)
                        displayResponseValidationErrors(response);
                }

                swapLoadingIcon(false, "saveButton");
            });
    };

    function displayResponseValidationErrors(response) {
        for (var i = 0; i < response.errors.length; i++) {
            var span = document.getElementById(response.errors[i].Key + "-validation");
            errorText = document.createTextNode(response.errors[i].Value);
            if (span)
                span.appendChild(errorText);
        }
    }

    function clearValidationErrors() {
        $(".field-validation-valid").text(' ');
    }

    function parseJsonDate(jsonDateString) {
        if (jsonDateString)
            return new Date(parseInt(jsonDateString.replace('/Date(', ''))).toLocaleDateString();
        else
            return "";
    }
}