﻿(function ($) {
    $.extend($.rcn, {
        membership: {
            suppressLoginEvent: function () {
                jQuery.rcn.settings.triggers['login'] = false;
            },
            isLoggedIn: function () {
                return $.rcn.settings.isLoggedIn;
            },
            login: function (username, password, onSuccess, onError) {
                var url = jQuery.rcn.settings.url.login
                    + "?username=" + encodeURIComponent(username)
                    + "&password=" + encodeURIComponent(password)
                    + "&cid=" + jQuery.rcn.settings.cacheKey
                    + "&method=?";

                $.getJSON(url, function (isLoggedIn, textStatus) {
                    if (isLoggedIn) {
                        onSuccess();
                        jQuery.rcn.resetCache();
                        if (jQuery.rcn.settings.triggers['login'])
                            jQuery.rcn.trigger(jQuery.rcn.events.loggedIn);
                    }
                    else
                        onError(textStatus);
                });
            },
            createUser: function (username, password, acceptNewsLetter, onSuccess, onError) {
                var url = jQuery.rcn.settings.url.createUser
                    + "?username=" + encodeURIComponent(username)
                    + "&password=" + encodeURIComponent(password)
                    + "&acceptNewsLetter=" + acceptNewsLetter
                    + "&cid=" + jQuery.rcn.settings.cacheKey
                    + "&method=?";

                $.ajax({
                    url: url,
                    type: "GET",
                    dataType: "json",
                    success: function (messages, textStatus) {
                        onSuccess(messages);
                        if (messages.Errors.length == 0) {
                            jQuery.rcn.trigger(jQuery.rcn.events.loggedIn, { isUserRegistration: true });
                        }
                    },
                    error: function (XMLHttpRequest, textStatus, errorThrown) {
                        onError();
                    }
                });
                jQuery.rcn.resetCache();
            },
            addToWishlist: function (productId, variantId, onSuccess, onError) {
                $.post(jQuery.rcn.settings.url.addToWishlist,
                {
                    "productId": productId,
                    "variantId": variantId
                },
                function (data) {
                    if (data && data.Errors.length == 0) {
                        if (data && onSuccess)
                            onSuccess(data);
                    }
                    else if (onError)
                        onError(textStatus);
                });
            }
        }
    });
})(jQuery);

