/* global Bdf,Ficheform,$$ */

Ficheform.Init = {};

Ficheform.Init.date = function () {
    var dateInputsType = Ficheform.getOption("dateInputs");
    var noTab = Ficheform.getOption("noTab");
    $$({ficheformEntry: "date-unique"}).each(function (index, element) {
        let $entry = $(element);
        let input = $$.one($entry, {ficheformRole: "textinput"});
        let genId = Bdf.replaceWithDateInputs(input, dateInputsType);
        $$($entry, {ficheformRole: "label"}).attr("for", genId + "_year");
        var buttonTemplate;
        if (genId) {
            buttonTemplate = "bdf:button-dateinputs";
        } else {
            buttonTemplate = "bdf:button-transparent";
        }
        let buttonId = Bdf.generateId();
        $(input).parent().append(Bdf.render(buttonTemplate, {
            buttonId: buttonId,
            action: "action-CurrentDay",
            locKey: "_ link.pioche.currentday",
            noTab: noTab
        }));
        $$(buttonId).click(function () {
            let currentVal = $(input).val();
            if (currentVal) {
                let ok = confirm(Bdf.Loc.get("_ warning.edition.currentdayupdate", currentVal));
                if (!ok) {
                    return;
                }
            }
            let currentTime = new Date();
            let year = currentTime.getFullYear();
            let month = currentTime.getMonth() + 1;
            let day = currentTime.getDate();
            $(input).val(Bdf.joinDate(year, month, day));
            if (genId) {
                $$(genId, "year").val(year);
                $$(genId, "month").val(month);
                $$(genId, "day").val(day);
            }
        });
    });
    
};

Ficheform.Init.geocodage = function () {
    $$({ficheformEntry: "geocodage"}).each(function (index, element) {
        let $entry = $(element);
        let buttonId = Bdf.generateId();
        let latitudeId = $$.one($entry, {ficheformRole: "latitude"}).id;
        let longitudeId = $$.one($entry, {ficheformRole: "longitude"}).id;
        let startLatitude = "";
        let startLongitude = "";
        let startZoom = "";
        if (element.dataset.ficheformGeostartLat) {
            startLatitude = element.dataset.ficheformGeostartLat;
        }
        if (element.dataset.ficheformGeostartLon) {
            startLongitude = element.dataset.ficheformGeostartLon;
        }
        if (element.dataset.ficheformGeostartZoom) {
            startZoom = element.dataset.ficheformGeostartZoom;
        }
        $entry.find("tr:first").append(Bdf.render("ficheform:geocodage", {
            buttonId: buttonId,
            noTab: Ficheform.getOption("noTab")
        }));
        $$(buttonId).click(function () {
            _piocheGeocodage(latitudeId, longitudeId, $entry.data("ficheformAddressfields"), startLatitude, startLongitude, startZoom);
        });
    });
    
    
    function _piocheGeocodage(latitudeId, longitudeId, addressFields, startLatitude, startLongitude, startZoom) {
        let lat = $$.one(latitudeId).value;
        let lon = $$.one(longitudeId).value;
        let noCurrent = false;
        if (!lat) {
            lat = startLatitude;
            noCurrent = true;
        }
        if (!lon) {
            lon = startLongitude;
        }
        let appelant = latitudeId + "," + longitudeId;
        let url = "pioche?page=geocodage&appelant="+ appelant + "&lat=" + encodeURIComponent(lat) + "&lon=" + encodeURIComponent(lon);
        if (addressFields) {
            url = url + "&addressfields=" + addressFields;
        }
        if (startZoom) {
            url = url + "&zoom=" + startZoom;
        }
        if (noCurrent) {
            url = url + "&nocurrent=1";
        }
        Ficheform.openDialog(url,"pioche_geocodage",620,660);
    }
};

Ficheform.Init.grouped = function () {
    $$({_element: "input", ficheformGrouped: "1"}).each(function (index, element) {
        if (element.checked) {
            $(element).parent().addClass("ficheform-SelectedLabel");
        }
        $(element).change(_testChange);
    });
    
    
    function _testChange() {
        let type = this.type;
        if (type === "radio") {
            let name = this.name;
            $$({_element: "input", _name: name}).parent().removeClass("ficheform-SelectedLabel");
        }
        $(this).parent().toggleClass("ficheform-SelectedLabel", this.checked);
    }
};

Ficheform.Init.mandatory = function () {
    var $mandatoryList = $$({ficheformMandatory: "1"});
    $$($mandatoryList, {ficheformRole: "label"}).append(Bdf.render("ficheform:mandatoryicon"), {});
};

Ficheform.Init.piocheitem = function () {
    _initByPage("language","language-code","action-ficheform-Lang","_ link.pioche.language");
    _initByPage("country","country-code","action-ficheform-Country","_ link.pioche.country");
    _initByPage("user","user-code","action-ficheform-User","_ link.pioche.user");


    function _initByPage(page, entryType, action, locKey) {
         $$({ficheformEntry: entryType}).each(function (index, element) {
            let entryKey = element.dataset.ficheformKey;
            let buttonId = Bdf.generateId();
            let $input = $$(element, {ficheformRole: "textinput"});
            let inputId = $input.attr("id");
            $input.after(Bdf.render("bdf:button-transparent32", {
                buttonId: buttonId,
                action: action,
                locKey: locKey,
                noTab: Ficheform.getOption("noTab")
            }));
            $$(buttonId).click(function () {
                _piocheItem(page, entryKey, inputId);
            });
        });
    }
    
    function _piocheItem(page, entryKey, inputId) {
        let entry = Ficheform.entry(entryKey);
        let limit = entry.dataset.ficheformLimit;
        if (!limit) {
            limit = -1;
        }
        let url = "pioche?page=" + page + "&appelant=" + inputId + "&limit=" + limit + "&subsets=";
        let defaultsphere = entry.dataset.ficheformDefaultsphere;
        if (defaultsphere) {
            url = url + "&defaultsphere=" + defaultsphere;
        }
        Ficheform.openDialog(url,"pioche_" + entryKey,430,510);
    }
};

Ficheform.Init.maxlength = function () {
    $$({ficheformEntry: "text-maxlength"}).each(function (index, element) {
        let $input = $$(element, {ficheformRole: "textinput"});
        let maxLength = parseInt($input.attr("maxlength"));
        if (maxLength > 0) {
            let inputlengthId = Bdf.generateId();
            let startLength = $input.val().length;
            $input.after(Bdf.render("ficheform:maxlength", {
               inputlengthId: inputlengthId,
               maxLength: maxLength,
               startLength: startLength
            }));
            _checkClasses($input, $$(inputlengthId), startLength, maxLength);
            $input.on("input", function () {
                let $this = $(this);
                let newLength = $this.val().length;
                $$(inputlengthId, "length").text(newLength);
                _checkClasses($this, $$(inputlengthId), newLength, maxLength);
            });
        }
    });
    
    
    function _checkClasses($input, $inputLength, currentLength, maxLength) {
        if (currentLength > maxLength) {
            $input.removeClass("ficheform-MaxReached").addClass("ficheform-MaxExceeded");
            $inputLength.removeClass("ficheform-MaxReached").addClass("ficheform-MaxExceeded");
        } else if (currentLength === maxLength) {
            $input.addClass("ficheform-MaxReached").removeClass("ficheform-MaxExceeded");
            $inputLength.addClass("ficheform-MaxReached").removeClass("ficheform-MaxExceeded");
        } else {
            $input.removeClass("ficheform-MaxReached").removeClass("ficheform-MaxExceeded");
            $inputLength.removeClass("ficheform-MaxReached").removeClass("ficheform-MaxExceeded");
        }
    }
    
};


$(function () {
    Bdf.initTemplates();
    Ficheform.Init.date();
    Ficheform.Init.geocodage();
    Ficheform.Init.grouped();
    Ficheform.Init.mandatory();
    Ficheform.Init.piocheitem();
    Ficheform.Init.maxlength();
    Ficheform.ThesaurusInclude.init();
    Ficheform.CorpusInclude.init();
    Ficheform.Section.init();
    Ficheform.AlbumInclude.init();
    Ficheform.AddendaInclude.init();
    Ficheform.Toc.init();
    Ficheform.init(Ficheform.ARGS.goto);
    Bdf.Shortcut.init();
});