﻿

(function ($) {
    $.widget("nmk.createaccount", {
        options: {
            identifier: "",
            arrangemangbokningdeltagare: 0,
            session: "",
            chk: "",
            close: true,
            callbackRefresh: function () { },
            user: function (user) { },
            callbackSuccess: function () { },
            callbackAvbryt: function () { },
            createButtonText: "Slutför",
            confirmCreate: true,
            confirmIntegritet: true,
            title: "Skapa konto",
            allowexist: true,
            loginStartCallback: function () { },
            deviceId: "",
            bundleId: "",
            returnUrl: ""
        },
        url: 'json/createaccount.ashx',
        currentStatus: 0,
        refresh: function (options2) {
            if (options2)
                this.options = $.extend({}, options2);
            this._load();
        },
        _create: function () {
            this.randomnr = randomFromInterval(0, 99999);
            this._load();
        },
        _ajax: function (detta, item, callback) {
            if (item.title == undefined) {
                item.title = "";
            }
            item.session = detta.options.session;
            item.identifier = detta.options.identifier;
            item.arrangemangbokningdeltagare = detta.options.arrangemangbokningdeltagare;
            item.bundle = detta.options.bundleId;
            item.deviceId = detta.options.deviceId;
            item.chk = detta.options.chk;
            if (item.title.length > 0)
                loadingBar(true, 1, "Vänta...", item.title + "...");
            $.ajax({
                url: detta.url,
                error: function (xhr, textStatus, errorThrown) {
                    if (item.title.length > 0)
                        loadingBar(false, 1);
                },
                cache: false,
                data: item,
                type: "POST"
            }).done(function (data) {
                var obj = $.parseJSON(data);
                if (item.title.length > 0)
                    loadingBar(false, 1);
                callback(obj);
                if (obj.checkitem) {
                    detta.options.user(obj.checkitem.medlem);
                }
            });
        },
        item: null,
        _load: function () {
            this.element.empty();
            var detta = this;
            var buttons = [];
            detta.currentStep = 0;

            var setSteps = function (step) {

                dialog.getButton('next').enable();
                detta.person.hide();
                divintegritet.hide();
                dialog.getButton('previous').disable();
                dialog.getButton('next').text('Fortsätt'.translate());
                switch (step) {
                    case 0:
                        detta.person.show();
                        detta.currentStep = 0;
                        break;
                    case 1:
                        if (detta.person.person('getperson') == null) {
                            detta.person.show();
                            detta.person.person('check', function (res) {

                            });
                            return;
                        }
                        if (detta.person.person('validate') == false) {
                            detta.person.show();
                            return;
                        }
                        if (detta.options.confirmIntegritet == false) {
                            createAccount(true, function () {
                                dialog.close();
                            });
                            return;
                        }
                        divintegritet.show();
                        if (chkIntegritet.is(":checked")) {
                            dialog.getButton('next').enable();
                        } else {
                            dialog.getButton('next').disable();
                        }
                        detta.currentStep = 1;
                        dialog.getButton('next').text(detta.option.createButtonText);
                        dialog.getButton('previous').enable();
                        break;
                }
            };

            buttons.push({
                id: "previous",
                label: 'Tillbaka'.translate(),
                cssClass: 'btn-primary',
                //autospin: true,
                action: function (dialogRef) {
                    setSteps(detta.currentStep - 1);
                }
            });

            var createAccount = function (nyhetsbrev, callback) {
                if (detta.person.person('getpassportnumber')) {
                    var item = new Object();
                    item.command = "createaccount";
                    item.title = "Skapar konto".translate();
                    item.person = detta.person.person('getpersonuppgifterstr');
                    item.nyhetsbrev = nyhetsbrev;
                    detta._ajax(detta, item, function (obj) {
                        if (obj.resultat == false) {
                            if (obj.demandlogin) {

                                BootstrapDialog.show({
                                    message: 'Nu ska du som bokare logga in för att vi ska veta att det är rätt person som ändrar i bokningen.',
                                    buttons: [{
                                        label: 'Fortsätt',
                                        title: 'Klicka här för att fortsätta',
                                        action: function (dialogRef) {
                                            dialogRef.close();
                                            $("<div/>").bankid({
                                                user: function (user) {
                                                    detta.options.user(user);
                                                },
                                                loadCallback: detta.options.loginStartCallback,
                                                session: session,
                                                dialog: true,
                                                onFinnish: function (obj) {
                                                    if (obj.medlem) {
                                                        detta.options.user(obj.medlem);
                                                    }
                                                    createAccount(nyhetsbrev, callback);

                                                },
                                                redaninloggad: function (user) {
                                                    detta.options.user(user);
                                                    createAccount(nyhetsbrev, callback);
                                                }

                                            });
                                        }
                                    }]
                                });


                            } else {
                                BootstrapDialog.alert(obj.text);
                            }
                            return;
                        }
                        callback();
                        if (detta.options.confirmCreate) {
                            BootstrapDialog.show({
                                message: obj.text,
                                buttons: [{
                                    label: 'Fortsätt'.translate(),
                                    cssClass: 'btn-primary',
                                    //autospin: true,
                                    action: function (dialogRef) {
                                        dialogRef.close();
                                        detta.options.callbackSuccess(obj.medlem);
                                        if (obj.appSession) {
                                            dialog.close();
                                            if (obj.appSession.length > 0) {
                                                if (detta.options.returnUrl.length > 0) {
                                                    var returnUrl = new URL(detta.options.returnUrl);
                                                    returnUrl.searchParams.append("token", obj.appSession);
                                                    window.location.replace(returnUrl.toString());
                                                }
                                            }
                                        }
                                    }
                                }]
                            });
                        } else {
                            if (obj.appSession) {
                                dialog.close();
                                if (obj.appSession.length > 0) {
                                    if (detta.options.returnUrl.length > 0) {
                                        var returnUrl = new URL(detta.options.returnUrl);
                                        returnUrl.searchParams.append("token", obj.appSession);
                                        window.location.replace(returnUrl);
                                    }
                                }
                            }
                        }


                    });
                } else {
                    $("<div/>").bankid({
                        overridebankid: true,
                        create: true,
                        dialog: true,
                        bundle: detta.options.bundleId,
                        deviceId: detta.options.deviceId,
                        title: "Bekräfta ditt konto",
                        user: function (user) {
                            detta.options.user(user);
                        },
                        folkbokforingsadress: detta.person.person('getpersonuppgifterstr'),
                        faktureringsadress: "",
                        session: detta.options.session, personnummer: detta.person.person('getpersonuppgifter').personnr, onFinnish: function (obj) {
                            detta.options.callbackSuccess(obj.medlem);
                            dialog.close();
                            callback();
                            if (obj.appSession) {
                                if (obj.appSession.length > 0) {
                                    if (detta.options.returnUrl.length > 0) {
                                        var returnUrl = new URL(detta.options.returnUrl);
                                        returnUrl.searchParams.append("token", obj.appSession);
                                        window.location.replace(returnUrl);
                                    }
                                }
                            }
                        }
                    });
                }
            }


            buttons.push({
                id: "next",
                label: 'Fortsätt'.translate(),
                cssClass: 'btn-primary',
                //autospin: true,
                action: function (dialogRef) {
                    if (detta.currentStep == 1) {
                        createAccount(chkNyhetsbrev.is(":checked"), function () {
                            dialogRef.close();
                        });
                        return;
                    }
                    setSteps(detta.currentStep + 1);
                }
            });
            var divDialog = $("<div/>");

            detta.person = $("<div/>").person({
                session: detta.options.session, allowexist: detta.options.allowexist, exists: function () {
                    if (detta.options.arrangemangbokning === 0) {
                        BootstrapDialog.alert("Kontot finns redan registrerat. Logga in med ditt BankID.".translate());
                        dialog.close();
                    }

                }
            }).appendTo(divDialog);

            var divintegritet = $("<div/>").appendTo(divDialog).hide();

            var ul = $("<ul/>").addClass("list-group").appendTo(divintegritet);
            var li = $("<li/>").addClass("list-group-item text-right").appendTo(ul);

            var chkIntegritet = $("<input/>").attr("type", "checkbox").appendTo(li).change(function () {
                if (chkIntegritet.is(":checked")) {
                    dialog.getButton('next').enable();
                } else {
                    dialog.getButton('next').disable();
                }

            });
            $("<label/>").text(" " + "Läs och godkänn vår".translate() + " ").prepend(chkIntegritet).appendTo(li);
            $("<a/>").html(" " + "Integritetspolicy".translate()).appendTo(li).click(function (e) {
                $("<div/>").integritetspolicy({
                    type: "PDF",
                    session: detta.options.session,
                    user: function (user) {
                        detta.options.user(user);
                    }
                });
            });
            li = $("<li/>").addClass("list-group-item text-right").appendTo(ul);
            var chkNyhetsbrev = $("<input/>").attr("type", "checkbox").appendTo(li).prop("checked", true);
            $("<label/>").text(" " + "Jag godkänner att ni kontaktar mig via mail eller sms med nyheter och erbjudanden.".translate()).prepend(chkNyhetsbrev).appendTo(li);

            buttons.push({
                label: 'Avbryt'.translate(),
                cssClass: 'btn-warning pull-left',
                //autospin: true,
                action: function (dialogRef) {
                    dialogRef.close();
                    detta.options.callbackAvbryt();
                }
            });

            var dialog = new BootstrapDialog({
                title: detta.options.title,
                message: divDialog,
                onshown: function (dialog) {
                    dialog.getButton('previous').disable();

                },
                buttons: buttons,
                closable: detta.options.close,
            });
            dialog.open();
        },
        destroy: function () {
            this.element.empty();
            // Call the base destroy function.
            $.Widget.prototype.destroy.call(this);
        }
    });
})(jQuery);