﻿var employerId;
var siteName;
var jobPostingId;
var jobCategoryId;
var siteUserId;
var path = "/ajax/registration.aspx";
var registrationPage = "/Registration/AttApplicant_Reg_02.aspx";

$.blockUI.defaults.overlayCSS.opacity = 0.1;
$.blockUI.defaults.message = '';

$(document).ready(function () {

    employerId = $("#serverdata").data("employerid");
    siteName = $("#serverdata").data("sitename");
    jobPostingId = $("#serverdata").data("jobpostingid");
    jobCategoryId = $("#serverdata").data("jobcategoryid");

    $("#registeredEmail").keypress(function (event) {
        if (event.which == 13)
            getVerificationCode();
    });
    $("#txtVerificationCode").keypress(function (event) {
        if (event.which == 13)
            verify();
    });

    $("#invalidcode").hide();
    $("#invalidemail").hide();
    $("#invalidaccount").hide();
    $("#invalidlogin").hide();

    jQuery("#btnGetCode").click(function () {
        getVerificationCode();
    });

    jQuery("#lnkGetCode").click(function () {
        getVerificationCode();
    });

    jQuery("#btnLinkAccount").click(function () {
        Register();
    });

    jQuery("#btnCreateNewAccount").click(function () {
        btnCreateNewAccountClick();
    });

    jQuery("#btnVerify").click(function () {
        verify();
    });

    jQuery("#btnContinue").click(function () {
        show_overlay_message("");
        Logon();
    });

    jQuery("#btnFindAccount").click(function () {
        FindAccount();
        $('#VerificationSucceed').modal('hide');
    });

    jQuery("#btnCreateAccount").click(function () {
        CreateNewAccount(true);
    });
    
    jQuery("#btnCreateNew").click(function () {
        window.location = registrationPage + "?JOB_POSTING_ID=" + jobPostingId + "&jcid=" + jobCategoryId;
    });
    jQuery("#btnLinkAccount2").click(function () {
        siteUserId = $("input[name='accountlist']:checked").val();
        $('#invalidaccount').hide();
        $('#ConfirmCreateAccount').modal('hide');
    });

    jQuery("#VerificationDialog").on('shown.bs.modal', function () {
        //$("#invalidcode").hide();
        $("#txtVerificationCode").focus();
    });

    jQuery("#VerificationSucceed").on('shown.bs.modal', function () {
        $("#btnFindAccount").focus();
    });

    toggleScreen(true, false, false);

    $("#registeredEmail").focus();
});

function genericAlert(title, body) {
    $('#GenericAlertTitle').html(title);
    $('#GenericAlertBody').html(body);
    $('#GenericAlert').modal({ backdrop: 'static', keyboard: false }, 'show');
}

function btnCreateNewAccountClick() {
    if ($("#btnCreateNewAccount").attr("allAccountsLinked") == "true") {
        window.location = registrationPage;
    }
    else {
        $('#ConfirmCreateAccount').modal({ backdrop: 'static', keyboard: false }, 'show');
    }
    
}

function getVerificationCode() {
    var email = $("#registeredEmail").val().trim();
    if (!ValidateEmail(email)) {
        $("#invalidemail").show();
        return;
    }

    $("#invalidcode").hide();
    $("#invalidemail").hide();
    $("#txtVerificationCode").val("");

    $.blockUI();

    $.ajax({
        url: path,
        cache: false,
        dataType: "html",
        data: {
            requestType: "SendVerification",
            email: email,
            siteName: siteName
        },
        error: function (request, strStatus, exError) { $.unblockUI(); },
        success: function (Response, event) {
            $.unblockUI();
            if (Response == "1") {
                $('#VerificationDialog').modal({ backdrop: 'static', keyboard: false }, 'show');
                $("#invalidcode").hide();
            }
        }
    });

}

$(document).on("click", "#account-list input", function () {
    /*$("#account-list .list-group-item").each(function () {
        $(this).removeClass("active");
    });*/
    $("#account-list .list-group-item.active").removeClass("active");
    $(this).parent().parent().addClass("active");
});

function verify() {
    var code = $("#txtVerificationCode").val().trim();
    if (code == "") {
        $("#invalidcode").show();
        return;
    }

    $.blockUI();

    $.ajax({
        url: path,
        cache: false,
        dataType: "html",
        data: {
            requestType: "Verify",
            code: code
        },
        error: function (request, strStatus, exError) { $.unblockUI(); },
        success: function (data, event) {
            var response = JSON.parse(data);
            if (!response.success) {  // invalid verification code
                $("#invalidcode").show();
            }
            else {
                $("#invalidcode").hide();
                $('#VerificationDialog').modal('hide');
                $('#VerificationSucceed').modal({ backdrop: 'static', keyboard: false }, 'show');
                $("#btnFindAccount").attr("key", response.key);
            }
            $.unblockUI();
        }
    });

}

function FindAccount() {

    var email = $("#registeredEmail").val().trim();
    var key = $("#btnFindAccount").attr("key");
    
    $.ajax({
        url: path,
        cache: false,
        dataType: "html",
        type: "POST",
        async: false,
        data: {
            requestType: "FindAccount",
            jobCategoryId: jobCategoryId,
            email: email,
            key: key,
            employer_id: employerId,
            jobPostingId: jobPostingId
        },
        error: function (request, strStatus, exError) { $.unblockUI(); },
        success: function (Response, event) {
            var response = Response.split('|*|');
            if (response[7] == "False") {
                $('#VerificationDialog').modal({ backdrop: 'static', keyboard: false }, 'show');
                $("#invalidcode").show();
                return;
            }
            DisplayAccounts(response);
            $.unblockUI();
        }
    });
}

function DisplayAccounts(res) {
    var numberOfAccounts = res[0];
    var data = res[1];
    var hasAccount = res[2];
    var existingLoginname = res[3];
    var lastlogin = res[4];
    if (res[5] != "")
        siteUserId = res[5];

    var allAccountsLinked = res[6] == "True";

    if (data == "") {
        $("#enteredEmail").html($("#registeredEmail").val());
        CreateNewAccount(true);
    }
    else {
        if (hasAccount == "False") {
            $("#invalidaccount").hide();
            toggleScreen(false, true, false);
        }
        else {
            $("#existingLoginName").html(existingLoginname);
            $("#lastlogindate").html(lastlogin);
            toggleScreen(false, false, true);
        }

    }

    var title = "Create an Account";

    if (allAccountsLinked) {
        $("#btnLinkAccount").html("Continue");
        $("#btnCreateNewAccount").html("Create an Account");
        $("#btnCreateNewAccount").attr("allAccountsLinked", "true");

        if (numberOfAccounts > 1) {
            title = "Existing accounts found";
        }
        else {
            title = "Existing account found";
        }
        $("#lblLinkAccount").html(title);
    }
    else {
        $("#btnLinkAccount").html("Link Account");
        $("#btnCreateNewAccount").html("No, thanks");
        $("#btnCreateNewAccount").attr("allAccountsLinked", "false");
        $("#lblLinkAccount").html(title);
    }

    $("#account-list").html(data);
}

function CreateNewAccount(action) {
    if (action) {
        if (jobPostingId == "00000000-0000-0000-0000-000000000000") {
            window.location = registrationPage + "?email=" + $("#registeredEmail").val();
        }
        else {
            window.location = registrationPage + "?JOB_POSTING_ID=" + jobPostingId + "&jcid=" + jobCategoryId + "&email=" + $("#registeredEmail").val();
        }
    }
    else {
        $("#registeredEmail").val("");
        $("#txtVerificationCode").val("");
        toggleScreen(true, false, false);
    }
}

function Register() {
    siteUserId = $("input[name='accountlist']:checked").val();
    if (siteUserId == null) {
        $("#invalidaccount").show();
        return;
    }

    var applicantId = $("input[name='accountlist']:checked").attr("applicant_id");
    var loginname = $("input[name='accountlist']:checked").attr("login-name");

    $.blockUI();

    $.ajax({
        url: path,
        cache: false,
        dataType: "html",
        type: "POST",
        async: false,
        data: {
            requestType: "Register",
            site_user_id: siteUserId,
            applicant_id: applicantId,
            employer_id: employerId,
            jobPostingId: jobPostingId
        },
        error: function (request, strStatus, exError) { $.unblockUI(); },
        success: function (Response, event) {
            if (Response == "1") {
                
                window.location = "/WLSBLogin.aspx?SITE_USER_ID=" + siteUserId;
            }
            else
                $.unblockUI();
        }
    });
}

function Logon() {
    window.location = "/WLSBLogin.aspx?SITE_USER_ID=" + siteUserId;
}

function CreateAccount() {
    window.location = registrationPage + "?email=" + $("#registeredEmail").val();
}

function toggleScreen(email, accountlist, accountexists) {
    if (email)
        $("#reg-email").show();
    else
        $("#reg-email").hide();

    if (accountlist)
        $("#reg-accountlist").show();
    else
        $("#reg-accountlist").hide();

    if (accountexists)
        $("#reg-accountexists").show();
    else
        $("#reg-accountexists").hide();

}

function ValidateEmail(email) {
    if (/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(email)) {
        return (true)
    }
    return (false)
}

$(document).on("click", ".expand-employer-list", function (e) {
    e.preventDefault();

    var findclass = $(this).parent().find(".employer-list").hasClass("collapsed-list");
    if (findclass) {
        $(this).parent().find(".employer-list").removeClass("collapsed-list")
        $(this).html("show less");
    }
    else {
        $(this).parent().find(".employer-list").addClass("collapsed-list");
        $(this).html("show more");
    }
});

function show_overlay_message(message) {
    $(document).ready(function () {
        $(".overlay-wrapper").remove();

        overlaywrapper = $("<div>", { class: "overlay-wrapper" });
        overlay = $("<div>", { class: "overlay", style: "width:100%;height:100%;background:#000;opacity:0.2;position:fixed;z-index:1099;left:0;top:0;cursor:wait" }).appendTo(overlaywrapper);
        if (message) {
            overlaymsg = $("<div>", { class: "overlay-message", style: "width: auto;max-width: fit-content;max-width:500px;min-width: 300px;padding: 20px; text-align: center;background: #fff;border: 1px solid #ccc;border-radius: 4px;position: fixed;margin-left: auto;margin-right: auto;top: 50%; left: 0;right: 0;z-index: 2099;", html: "<i class=\"fa fa-spinner fa-spin\"></i> " + message }).appendTo(overlaywrapper);
        }
        $(overlaywrapper).appendTo("body");
        overlaywrapper.show();
    });
}
