﻿"use strict";
(function ($, window, document, undefined) {

    // default settings.
    var _pluginName = "prospects";
    var _sendMessageURL = "";
    var _recipient = "";
    var _defaultsOptions = {
        debug: false,
    };
    var _logger = new CsLogger(_pluginName);

    var _$form = null;

    // constructor.
    function Prospects(element, options) {
        this._element = element;
        _sendMessageURL = options.url;
        _recipient = options.recipient;
        _$form = $(options.form);

        // $.extend to store user provided options.
        this._options = $.extend({}, _defaultsOptions, options);
        this._defaultOptions = _defaultsOptions;
        this._name = _pluginName;
        this.init();
    }

    // (void) ensure the selected element is valid.
    function validateElement(element) {
        _logger.log("validateElement()");
        if (element == undefined || $(element).length == 0) {
            _logger.error("selected element is not valid.");
            return;
        }
    }

    // (void) validate the options passed into the plugin.
    function validateOptions(options) {
        if (typeof (options.debug) == "boolean" && options.debug == true) {
            _logger.enable();
        }
        _logger.obj("validateOptions() | opts:", options);
    }

    function bindControls(element) {

        var $sentNotif = $(element).find("#sent-message-prospects");
        var $sentNotifText = $sentNotif.find("#sent-message-text-prospects");

        var btnContact = $(element).find("#btn-prospects-contact");
        var btnCloseMessage = $(element).find("i.fa-times");

        $("#dob").mobiscroll().datepicker({
            controls: ['calendar'],
            dateFormat: 'DD/MM/YYYY',
            firstDay: 1
        });

        btnContact.on("click", function () {
            if (_$form.valid() == false) {
                return;
            }
            var token = $(element).find("input[name='__RequestVerificationToken']").val();
            var forename = $(element).find("#forename").val();
            var surname = $(element).find("#surname").val();
            var email = $(element).find("#email.form-control[type=email]").val();
            var pEmail = $(element).find("#pValidateEmail").val();
            var pValidateKey = $(element).find("#pValidateKey").val();
            var phone = $(element).find("#phone.form-control[type=tel]").val();
            var message = $(element).find("textarea.form-control").val();
            var gender = $(element).find("#gender").val();
            var recipient = _recipient;
            var selectedDateOfBirth = $("#dob").mobiscroll("getVal");
            
            if (selectedDateOfBirth instanceof Date) {
                
                selectedDateOfBirth = selectedDateOfBirth.toISOString().slice(0, 10);
            } else {
                
                selectedDateOfBirth = null;
            }

            var data =
            {
                "__RequestVerificationToken": token,
                "forename": forename,
                "surname": surname,
                "email": email,
                "gender": gender,
                "dateofbirth": selectedDateOfBirth,
                "PValidateEmail": pEmail,
                "PValidateKey": pValidateKey,
                "telephone": phone,
                "message": message,
                "sentdate": moment().format("DD/MM/YYYY kk:mm"),
                "recipient": recipient                                                                   
            };
             
            $sentNotif.removeClass("error sent");
            $sentNotif.hide();
            var result = validateFormData(data);
            $sentNotifText.text(result.info);

            if (result.isValid) {
                // fire ajax call to server:
                $.ajax({
                    async: true,
                    type: "post",
                    url: _sendMessageURL,
                    data: data,
                    success: function (resp) {
                        if (resp.success == true) {
                            $(element).find(".contact-form").remove();
                            $sentNotif.addClass("sent").fadeIn("fast");
                        }
                        else {
                            $sentNotif.addClass("error").fadeIn("fast");
                            $sentNotifText.text(resp.error);
                            // we can also add error message, which should be in the response object.
                        }
                    }
                });
            }
            else {
                // something went wrong with validation.
                // we won't hide the inputs when it's invalid, we'll just show an error message.
                $sentNotif.removeClass("sent").addClass("error").fadeIn("fast");
                $sentNotifText.text("Invalid data detected in your form, please check again and retry.");
            }
        });

        btnCloseMessage.on("click", function () {
            $sentNotif.fadeOut("fast");
        });
    }

    // (object) returns result of validation (unused).
    function validateFormData(data) {
        // this method was supposed to validate the form but
        // jquery validate takes care of that so we don't really need this.
        _logger.log(data);
        var result = {
            isValid: true,
            // default message:
            info: "Your message was sent successfully. Thanks.",
            invalidControls: []
        };
        return result;
    }

    // prototype extensions.
    Prospects.prototype = {

        // (void) initialise.
        init: function () {
            validateOptions(this._options);
            validateElement(this._element);
            _logger.log("init()");

            bindControls(this._element);
        }
    };

    // A really lightweight plugin wrapper around the constructor,
    // preventing against multiple instantiations
    $.fn[_pluginName] = function (options) {
        return this.each(function () {
            if (!$.data(this, "plugin_" + _pluginName)) {
                $.data(this, "plugin_" + _pluginName,
                    new Prospects(this, options));
            }
        });
    };

})(jQuery, window, document);


