"use strict";

let currentTab = 0;
$(() => {
    // TODO PAKE PARSLEY VALIDATION @iam
	$("#formPengajuan").parsley();

	showTab(currentTab);

	$(".form-perorangan").hide();
	$("input[name='jenis_pemohon']").on("click", function(e) {
		if(this.value === 'kuasa hukum') {
			$(".form-perorangan").show();
		} else {
			$(".form-perorangan").hide();
		}
	});

    const nomor_perkara_url = $('#nomor_perkara').attr('data-url');
    if(jQuery().select2) {
        $('#nomor_perkara').select2({
            language: "id",
            theme: "classic",
            minimumInputLength: 3,
            ajax: {
                url: nomor_perkara_url,
                dataType: 'json',
                type: "GET",
                delay: 300,
                data: function (params) {
                    return {
                        keyword: params.term,
                    };
                },
                processResults: function (data, page) {
                    return {
                        results: data
                    };
                }
            }
        });
    }
});

function showTab(n) {
    var x = document.getElementsByClassName("tab");
    x[n].style.display = "block";
    if (n == 0) {
        document.getElementById("prevBtn").style.display = "none";
    } else {
        document.getElementById("prevBtn").style.display = "inline";
    }
    if (n == x.length - 1) {
        document.getElementById("nextBtn").innerHTML = lang.confirm;
    } else {
        document.getElementById("nextBtn").innerHTML = lang.next_step;
    }
    fixStepIndicator(n);
}
function nextPrev(n) {
    var x = document.getElementsByClassName("tab");
    if (n == 1 && !validateForm()) return false;
    x[currentTab].style.display = "none";
    currentTab = currentTab + n;
    if (currentTab >= x.length) {
        document.getElementById("formPengajuan").submit();
        return false;
    }
    showTab(currentTab);
}
function validateForm() {
    var x,
        y,
        i,
        valid = true;
    x = document.getElementsByClassName("tab");
    y = x[currentTab].getElementsByTagName("input");
    for (i = 0; i < y.length; i++) {
        if (y[i].value == "") {
            y[i].className += " invalid";
            valid = false;
        }
    }
    if (valid) {
        document.getElementsByClassName("step")[currentTab].className +=
            " finish";
    }
    return true;
}
function fixStepIndicator(n) {
    var i,
        x = document.getElementsByClassName("step");
    for (i = 0; i < x.length; i++) {
        x[i].className = x[i].className.replace(" active", "");
    }
    x[n].className += " active";
}
