﻿/// <reference path="jquery-1.4.2-vsdoc.js" />
/* NOTE: This script requires that the AuthenticationControl.ascx be added
 * to the page (it's on the master page atm)
 *
 * The event that is fire when a user logs in is: "VictorAuthOnLogin"
     $('body').trigger('VictorAuthOnLogin', {
        userId: data.d.UserId, <- The Id of the user
        nickName: data.d.NickName <- The nickname of the user
        routeWatches: data.d.routeWatches <- the routes watched by this user (contains two fields: DepartureCode, ArrivalCode)
        rangeWatches: data.d.rangeWatches <- the routes with ranges watches by this user (containers four fields: DepartureCode, ArrivalCode, FromDate, ToDate)
     });
     
 *  The options that should be set in the AuthenticationInit:
    isAuthenticatedPath: <- path to service to check authentication status
    loginPath: <- path to service to authenticate the user attempting to log in
    registrationPath: <- path to registration page
    forgotPasswordPath: <- path to forgot password page
    
    additional options available:
    success: <- the function to be called on success
    failure: <- the function to be called on failure
    registrationParams: <- an object that contains what will be added to the return url e.g { fid: 123 } will be ?fid=123
 */
(function ($) {
    var AuthenticationOptions = null;

    $.AuthenticationInit = function (options) {
        AuthenticationOptions = options;
    }

    //Returns the UserData returned by the service or null if not logged in (hidden field is empty)
    $.AuthenticationGetUserData = function () {
        if (AuthenticationOptions == null) return null;
        var str = $(AuthenticationOptions.hiddenId).val();
        if (str == "") return null;

        var obj = JSON.parse(str);

        return obj;
    }

    $.AuthenticationSetUserData = function (userData) {
        $(AuthenticationOptions.hiddenId).val(JSON.stringify(userData));
    }

    $.AuthenticationUpdateUserData = function (success) {
        var args = JSON.stringify({});
        $.ajax({
            url: AuthenticationOptions.updateAuthDataPath,
            data: args,
            success: function (data) {
                if (data.d.updated) {
                    var $hidden = $(AuthenticationOptions.hiddenId);
                    $hidden.val(JSON.stringify(data.d.userData));
                }

                success();
            }
        });
    }

    //Demands authentication, 'onSuccess' will occur after and if the user successfully logs in, else 'onfailure' will occur
    //All variables are optional
    //optionsOrSuccessFunction: can be either a object that will replace the default settings set in AuthInit, 
    //                          it can also simply be a function which will be fired on success
    //onFailure: Fired if the user is not authenticated
    $.DemandAuthentication = function (optionsOrSuccessFunction, onFailure) {
        var _I = this;

        var options = AuthenticationOptions;
        var $hidden = $(options.hiddenId);

        //This checks if the first params is an object, and if it is, repaces the AuthOps with the values provided (only if they are provided hoever)
        if ($.isPlainObject(optionsOrSuccessFunction)) {
            options = $.extend(options, optionsOrSuccessFunction);

            var registrationParams = optionsOrSuccessFunction.registrationParams;
            if ($.isPlainObject(registrationParams) && !$.isEmptyObject(registrationParams)) {
                var paramsStr = AuthenticationOptions.registrationPath;
                //Split the string

                var first = true;
                for (var i in registrationParams) {
                    if (first) {
                        paramsStr += '?';
                        first = false;
                    }
                    else { paramsStr += '&'; }

                    paramsStr += i;
                    paramsStr += '=';
                    paramsStr += registrationParams[i];
                }
                options.registrationPath = paramsStr;
            }
        } else {
            //This assumes that if the first param is not an object, then it is a success function
            options.success = optionsOrSuccessFunction;
            options.failure = onFailure;
        }

        //Uses the jQuery emtpy function in its place - these paths aren't reliable so AuthenticationInit should always be called
        this.settings = $.extend({
            success: $.noop,
            failure: $.noop,
            complete: $.noop
        }, options || {});

        var args = JSON.stringify({});
        $.ajax({
            url: _I.settings.isAuthenticatedPath,
            data: args,
            success: function (data) {
                //Returns true if the user is signed in
                AfterInitialCheck(data.d.success);
            }
        });

        function AfterInitialCheck(isLoggedIn) {
            if (isLoggedIn) {
                OnReturn(true);
            } else {
                CreateLoginDialog();
            }
        }

        function CreateLoginDialog() {
            var sb = $('#logindialog').html();
            var title = $('#logintitle').html();
            $('<div>', {
                html: sb
            }).dialog({
                title: title,
                modal: true,
                width: 560,
                height: 330,
                dialogClass: 'victorAuthDialog',
                close: function () {
                    $(this).dialog('destroy');
                    OnReturn(false);
                },
                open: function () {
                    var $this = $(this).removeClass('ui-corner-all');

                    $this.find('a.victorAuthLogin').click(function () {
                        var $loading = $this.find('div.victorAuthLoading').show();
                        var $button = $(this).addClass('buttonAjaxLoader');

                        var args = JSON.stringify({
                            username: $this.find('input.victorAuthUsername').val(),
                            password: $this.find('input.victorAuthPassword').val(),
                            remember: $this.find('input.victorAuthRemember').is(':checked')
                        });

                        $.ajax({
                            url: _I.settings.loginPath,
                            data: args,
                            success: function (data) {
                                $loading.hide();
                                $button.removeClass('buttonAjaxLoader');

                                if (data.d.success) {
                                    //Sets the hidden input field
                                    $hidden.val(JSON.stringify(data.d.userData));
                                    //triggers auth event
                                    $('body').trigger('VictorAuthOnLogin', {
                                        userId: data.d.userData.userId,
                                        nickName: data.d.userData.nickName,
                                        routeWatches: data.d.userData.routeWatches,
                                        rangeWatches: data.d.userData.rangeWatches
                                    });

                                    OnReturn(true);
                                    $this.dialog('destroy');
                                } else {
                                    $this.find('.message').hide().fadeIn(300);
                                }
                            }
                        });
                    });
                }
            });
        }

        //Runs the success or the failure method depending on success or failure (obviously)
        //Runs the complete method
        function OnReturn(success) {
            if (success) _I.settings.success();
            else _I.settings.failure();
            _I.settings.complete();
        }
    }
})(jQuery);
