﻿/// <reference path="~/Scripts/jquery-2.1.4.intellisense.js" />
/// <reference path="../../Scripts/pnotify.custom.js" />
/// <reference path="~/Scripts/knockout-3.3.0.debug.js" />
/// <reference path="~/Scripts/knockout.mapping-latest.debug.js" />
/// <reference path="~/Scripts/knockout.validation.js" />
/// <reference path="~/CSI/UAM/Scripts/dataSources.js" />
/// <reference path="~/Scripts/url.min.js" />
/// <reference path="~/Scripts/pnotify.custom.js" />
/// <reference path="~/CSI/UAM/Scripts/configuration.js" />
(function (csi, $) {
    (function (views) {
        views.register = function () {
            var errorHandler = function (jqXhr, textStatus) {
                // ReSharper disable once UnusedLocals
                var notification = new PNotify({ text: textStatus, type: "error" });
                $("#unexpectedError").fadeIn();
                console.log(textStatus);
            };
            //var response = new responseViewModel();
            //var postNotificationMessage = function (message, type) {
            //    // ReSharper disable once UnusedLocals
            //    var notification = new PNotify({ text: message, type: type });
            //    response.message(message);
            //};
            var responseViewModel = function () {
                var self = this;
                self.message = ko.observable();
            }
            var response = new responseViewModel();
            var postAlert = function (message) {
                response.message(message);
            };
            var postNotificationMessage = function (message, element) {
                var notice = new PNotify({
                    text: element ? "<span class=\"x-ui-pnotify-text\">" + message + "</span>" : message, type: "error"
                });
                if (element) {
                    notice.get().click(function (e) {
                        if ($(e.target).is(".ui-pnotify-closer *, .ui-pnotify-sticker *")) return;
                        notice.remove();
                        $("input[id=" + element + "]").focus();
                    });
                }
            };
            var waiting = function (isLoading) {
                if (isLoading) {
                    $(".loading-image").show();
                    $(".btn").attr("disabled", "disabled");
                } else {
                    $(".loading-image").hide();
                    $(".btn").removeAttr("disabled");
                }
            };
            var validateRequest = function (requestId) {
                waiting(true);
                $.when(csi.accountManagement.dataSources.account.isContactFromSiteRegistration(requestId), csi.accountManagement.dataSources.account.wasRecoverPasswordEmailSent(requestId))
                    .always(function () {
                        waiting(false);
                    })
                    .done(function (isContact, wasEmailSent) {
                        if (!isContact[0]) {
                            $("#siteRegistrationForm").fadeOut("slow", function () { $("html, body").animate({ scrollTop: 0 }, 'slow'); $("#contactNotFound").fadeIn(); });
                        } else if (wasEmailSent[0]) {
                            $("#siteRegistrationForm").fadeOut("slow", function () { $("html, body").animate({ scrollTop: 0 }, 'slow'); $("#thankYou").fadeIn(); });
                        } else {
                            $("#siteRegistrationForm").fadeOut("slow", function () { $("html, body").animate({ scrollTop: 0 }, 'slow'); $("#unexpectedError").fadeIn(); });
                        }
                    })
                    .fail(function (jqXhr, textStatus) {
                        errorHandler(jqXhr, textStatus);
                    });
            };
            var init = function (serviceBaseAddress) {
                csi.accountManagement.dataSources.routes.init(serviceBaseAddress);
                var unlock = function (doesUserNameExist) {
                    if (doesUserNameExist) {
                        $("#userName1").parent().next(".help-block").children("p").html("This user name is already in use. Please try another.").show();
                        $("#unlock1").slideUp();
                    } else {
                        $("#unlock1").slideDown();
                    }
                };
                ko.validation.rules["uniqueUserName"] = {
                    async: true,
                    validator: function (val, parms, callback) {
                        if (val !== undefined)
                            csi.accountManagement.dataSources.account.doesUserNameExist(val)
                                .done(function (result) {
                                    var doesUserNameExist = JSON.parse(result.data).doesUserNameExist;
                                    callback(!doesUserNameExist);
                                    if (csi.accountManagement.clients && csi.accountManagement.client === csi.accountManagement.clients.SocietyAcademicEmergencyMedicine) {
                                        unlock(doesUserNameExist);
                                    }
                                })
                                .fail(function () {
                                    callback(false);
                                });
                    },
                    message: "That user name is already in use. Please try again."
                };
                ko.validation.registerExtenders();
                var siteRegistrationViewModel = function (companies) {
                    var self = this;
                    self.companies = ko.mapping.fromJS(companies);
                    self.company = ko.observable().extend({ maxLength: 80, required: true });
                    self.email = ko.observable().extend({ email: true, required: true });
                    self.firstName = ko.observable().extend({ required: true, maxLength: 20 });
                    self.lastName = ko.observable().extend({ maxLength: 30, required: true });
                    self.initLastName = ko.observable().extend({ maxLength: 30, required: true });
                    self.memberId = ko.observable().extend({ maxLength: 15, required: true });

                    self.validatedViewModel = ko.validatedObservable(self);
                    self.submitContact = function () {
                        if (!self.validatedViewModel.isValid()) {
                            self.validatedViewModel.errors.showAllMessages(true);
                            return false;
                        }

                        waiting(true);
                        csi.accountManagement.dataSources.account.createSiteRegistration(self.email(), self.firstName(), self.lastName(), self.initLastName(), self.memberId() || "", self.company() || "")
						    .always(function () {
						        waiting(false);
						    })
                            .done(function (result) {
                                if (result.status === "error") {
                                    postNotificationMessage(result.message, "error");
                                } else if (result.status === "fail") {
                                    $("#siteRegistrationForm").fadeOut("slow", function () { $('html, body').animate({ scrollTop: 0 }, 'slow'); $("#contactNotFound").fadeIn(); });
                                    postNotificationMessage(result.data, "error");
                                } else if (result.status === "success") {
                                    validateRequest(JSON.parse(result.data).requestId || "");
                                }
                            })
                            .fail(function (jqXhr, textStatus) {
                                errorHandler(jqXhr, textStatus);
                                response.showAllMessages(true);
                                $.each($(".validationMessage:visible:not(:empty)"), function (index, error) {
                                    pushErrorNotification("<b>" + $(error).parent().parent().children("label").text() + "</b>" + $(error).text(), $(error).parent().parent().children("label").attr("for"));
                                });
                            });
                        return true;
                    };
                };
                var token = URI(window.location.href).query(true).token;
                var createCredentialsViewModel = function (contactId, userName) {
                    var self = this;
                    self.userName = ko.observable().extend({ rateLimit: 500, uniqueUserName: self, required: true });
                    self.userName(userName); // Initializion after instantiation prevents a second validation request on the initial value.
                    self.password = ko.observable().extend({
                        minLength: { message: "Please enter at least 7 characters and a combination of letters and numbers.", params: 7 },
                        required: true,
                        pattern: {
                            message: "Invalid password. Please use a combination of letters and numbers.",
                            params: /(?=(^((?!(#|%|&apos;|&quot;|\s)).)*$))(?=.{7,})(?=(.*\d){1,})/
                        }
                    });
                    self.confirm = ko.observable().extend({ equal: self.password, required: true });
                    self.isLocked = ko.observable(csi.accountManagement.clients && csi.accountManagement.client === csi.accountManagement.clients.SocietyAcademicEmergencyMedicine);
                    self.validatedViewModel = ko.validatedObservable(self);
                    self.submit = function () {
                        if (!self.validatedViewModel.isValid()) {
                            self.validatedViewModel.errors.showAllMessages(true);
                            return false;
                        }

                        waiting(true);
                        csi.accountManagement.dataSources.account.updateSiteRegistration(contactId, self.password(), token, self.userName())
						    .always(function () {
						        waiting(false);
						    })
                            .done(function (result) {
                                if (result.status === "error") {
                                    postNotificationMessage(result.message, "error");
                                } else if (result.status === "fail") {
                                    postNotificationMessage(result.data, "error");
                                } else if (result.status === "success") {
                                    window.location = "/";
                                }
                            })
                            .fail(function (jqXhr, textStatus) {
                                errorHandler(jqXhr, textStatus);
                                response.showAllMessages(true);
                                $.each($(".validationMessage:visible:not(:empty)"), function (index, error) {
                                    pushErrorNotification("<b>" + $(error).parent().parent().children("label").text() + "</b>" + $(error).text(), $(error).parent().parent().children("label").attr("for"));
                                });
                            });
                        return true;
                    };
                };
                ko.validation.configure({
                    decorateElement: true,
                    insertMessages: false
                });
                ko.applyBindings(response, document.getElementById("responseMessage"));
                if (token) {
                    $("form").on("invalid-form", function (e) {
                        console.log($(e.target).validate().errorList);
                    });
                    csi.accountManagement.dataSources.account.getContacts(token)
						.always(function () {
						    $("#initializing1").fadeOut();
						})
                        .done(function (result1) {
                            if (result1.status === "error") {
                                postNotificationMessage(result1.message, "error");
                            } else if (result1.status === "fail") {
                                postNotificationMessage(JSON.parse(result1.data).message, "error");
                            } else if (result1.status === "success") {
                                var contact = (JSON.parse(result1.data).contacts)[0];
                                var contactId = contact.id;
                                csi.accountManagement.dataSources.account.doesContactHaveCredentials(contactId, token)
                                    .done(function (result2) {
                                        if (result2.status === "error") {
                                            postNotificationMessage(result2.message, "error");
                                        } else if (result2.status === "fail") {
                                            postNotificationMessage(JSON.parse(result2.data).message, "error");
                                        } else if (result2.status === "success") {
                                            var userName = JSON.parse(result2.data).doesContactHaveCredentials;
                                            if (userName.length > 0) {
                                                $("#siteRegistrationForm").fadeOut("slow", function () { $("html, body").animate({ scrollTop: 0 }, "slow"); $("#isRegistered").fadeIn(); });
                                            } else {
                                                if (csi.accountManagement.clients && csi.accountManagement.client === csi.accountManagement.clients.SocietyAcademicEmergencyMedicine) {
                                                    userName = contact.email;
                                                }
                                                ko.applyBindings(new createCredentialsViewModel(contactId, userName), document.getElementById("createCredentialsForm"));
                                                $("#createCredentialsForm").slideDown();
                                            }
                                        }
                                    })
                                    .fail(function (jqXhr, textStatus) {
                                        errorHandler(jqXhr, textStatus);
                                    });
                            }
                        })
                        .fail(function (jqXhr, textStatus) {
                            errorHandler(jqXhr, textStatus);
                        });
                } else {
                    csi.accountManagement.dataSources.account.getCompanies()
						.always(function () {
						    $("#initializing1").fadeOut();
						})
                        .done(function (companies) {
                            ko.applyBindings(new siteRegistrationViewModel(JSON.parse(companies.data || companies[0].data).companies), document.getElementById("siteRegistrationForm"));
                            $("#siteRegistrationForm").slideDown();
                        })
                        .fail(function (jqXhr, textStatus) {
                            errorHandler(jqXhr, textStatus);
                        });
                }
            };

            return {
                init: init
            };
        }();
    }(csi.views = csi.views || {}));
}(window.csi = window.csi || {}, window.jQuery));
