var Fiff = {}
$(document).ready(function () {

    Fiff = {
        rootPath: '/',
        init: function (options) {
            $.extend(this, options)     
        },
        standardDialogSettings: function () {
            return {
                bgiframe: true,
                resizable: false,
                draggable: true,
                closeOnEscape: false,
                modal: true,
                overlay: { backgroundColor: "#999900", opacity: 0.5 }
            }
        },
        authorization: {
			submitCheckOnControls: function(selector) {
				$(selector).click(function(ev) {
					var button = this;
					if(button.hasCheckedIfUserIsLoggedOn) return true;
					button.hasCheckedIfUserIsLoggedOn = false
					Fiff.authorization.isUserLoggedOn(
						function (response) {
							if(response.result) {
								button.hasCheckedIfUserIsLoggedOn = true;
								button.click()
							}
							else
								Fiff.authorization.showLoginDialog()
						}
					)
					return false;
				})
			
			},
            logout: function () {
                $.ajax({
                    url: 'Services/AuthenticationHandler.aspx',
                    dataType: 'json',
                    type: 'POST',
                    data: {
                        m: 'Logout'
                    },
                    success: function (response) {
                    },
                    error: function (xhr, ajaxOptions, thrownError) {
                        alert(thrownError)
                    }
                })
            },
            sendPassword: function (username, callbackSuccess, callbackError) {
				$.ajax({
                    url: 'Services/AuthenticationHandler.aspx',
                    dataType: 'json',
                    type: 'POST',
                    data: {
                        m: 'SendPassword',
                        username: username
                    },
                    success: function (response) {
						if(response.result) {
							if(callbackSuccess) callbackSuccess(response);
						} else {
							if(callbackError) callbackError(response.message);
						}
                    },
	                error: function (xhr, ajaxOptions, thrownError) {
						
                        if(callbackError) callbackError(thrownError);
                    }
                })            
            },
            login: function (username, password, callbackSuccess, callbackError) {
				var ctx = this;
                $.ajax({
                    url: 'Services/AuthenticationHandler.aspx',
                    dataType: 'json',
                    type: 'POST',
                    data: {
                        m: 'Login',
                        username: username,
                        password: password
                    },
                    success: function (response) {
						if(response && response.result) {
							$(ctx).trigger('loginSuccess')
							if(callbackSuccess) callbackSuccess(response);
						} else {
							$(ctx).trigger('loginFailed')
							if(callbackError) callbackError(response.message);
						}
                    },
	                error: function (xhr, ajaxOptions, thrownError) {
						$(ctx).trigger('loginError')
                        if(callbackError) callbackError(thrownError);
                    }
                })
            },
            isUserLoggedOn: function (callbackSuccess, callbackError) {
                $.ajax({
                    url: 'Services/AuthenticationHandler.aspx',
                    dataType: 'json',
                    type: 'POST',
                    data: {
                        m: 'IsLoggedOn'
                    },
                    success: function (result, status, xhr) {
                        if(callbackSuccess) callbackSuccess(result);
                    },
                    error: function (xhr, ajaxOptions, thrownError) {
						if(callbackError) callbackError(xhr)
                        alert('Error: ' + response.responseText)
                    }
                })
            },
            doLogin: function() {
				var ctx = this
				
				Fiff.authorization.login(
					this.loginDialog.username.val(),
					this.loginDialog.password.val(),
					function (response) {					
						ctx.loginDialog.dlg.dialog("close");
						ctx.loginDialog = null
					}, 
					function (message) {
						alert(message)
					}
				)
            
            },
            loginDialog: null,
            showLoginDialog: function () {
				
                if (this.loginDialog == null) { 
					this.loginDialog = this.createLoginDialog() 
					$('body').append(this.loginDialog.dlg)
				}

                this.loginDialog.dlg.dialog($.extend(Fiff.standardDialogSettings(), {
                    title: 'Logg inn',
                    buttons:
                    {
                        'Ok': function () {
                            Fiff.authorization.doLogin();
                        },
                        'Glemt passord': function () {
                            $(this).dialog("close");
                            //$('#loginDialog').remove();
                            Fiff.authorization.showForgotPasswordDialog();
                        },
                        'Avbryt': function () {
                            //$('#loginDialog').remove();
                            $(this).dialog("close"); 
                        }
                    }
                })).dialog('open');

                this.loginDialog.username.focus();
            },
            createLoginDialog: function () {
				var ctx = this
                var dialog = {dlg: $('<div id="loginDialog"><p>Du har blitt logget ut av Fiff. Skriv inn ditt brukernavn og passord p&aring; nytt og vi logger deg inn igjen.</p><label for="username">Brukernavn</label><input type="text" id="username" name="username" class="text ui-widget-content ui-corner-all"/><br/><label for="password">Passord</label><input type="password" id="password" name="password" class="text ui-widget-content ui-corner-all"/><div id="error" name="error"></div></div>') }
				
				dialog.username = $(dialog.dlg).find("#username")
				dialog.username.keydown(function(e){
					if (e.keyCode == 13) {
						dialog.password.focus();
					}
				})
				
				dialog.password = $(dialog.dlg).find("#password")
				dialog.password.keydown(function(e){
					if (e.keyCode == 13) {
						ctx.doLogin()
					}
				})
				
                dialog.error = $(dialog).find("#error")
                dialog.error.html('Error!')
                
                return dialog;
            },
            showForgotPasswordDialog: function () {
				var ctx = this;
				
				if (this.forgotPasswordDialog == null) { 
					this.forgotPasswordDialog = this.createForgotPasswordDialog() 
					$('body').append(this.forgotPasswordDialog.dlg)
				}
				
                this.forgotPasswordDialog.dlg
                .dialog($.extend(Fiff.standardDialogSettings(), {
                    title: 'Glemt passord',
                    buttons:
                    {
                        'Send': function () { 
							//$('#forgotPasswordDialog').remove(); 
							ctx.sendPassword(ctx.forgotPasswordDialog.username.val())
							$(this).dialog("close"); 
						},
                        'Avbryt': function () { 
							//$('#forgotPasswordDialog').remove(); 
							$(this).dialog("close"); 
						}
                    }
                })).dialog('open');
            },
            createForgotPasswordDialog: function () {
				var ctx = this;
					var dialog = {dlg: $('<div id="forgotPasswordDialog"><p>Skriv inn ditt brukernavn og trykk på send passord.</p><label for="username">Brukernavn</label><input type="text" id="username" name="username" class="text ui-widget-content ui-corner-all"/></div>') }

					dialog.username = $(dialog.dlg).find("#username")

                return dialog;
            }
        }
    }
})
