﻿$(document).ready(function() {
    FindUser();
    InitLoginForm()
    $("#linkLoginInd").bind("click", function() { SwitchLoginForm(true); });
    $("#linkLoginComp").bind("click", function() { SwitchLoginForm(false); });
    $("#linkSwitch").bind("click", function() { SwitchLoginForm($.cookie('loginAs')); });
    $("#buttonClear").bind("click", function() { ClearLoginCookie(); });
    $("#buttonLogin").bind("click", function() { Login(); });
    $("#loginFormContainer").css({ "display": "block" });
    $("#txtLogin").focus();
});

function FindUser() {
    $.ajax({
        type: "POST",
        url: "/services/LoginService.svc/GetIdentity",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        data: {},
        success: function(data) {
            //alert(data.d);
            var user = (typeof data.d) == 'string' ? eval('(' + data.d + ')') : response.d;
            //alert(user);
            if (user.anonymous != true) $("#spanUserGreeting").html("Hello <a href='Login.aspx'>anonymous user</a>");
            else $("#spanUserGreeting").html("Hello " + user.username + " <a id='linkLogout' onclick='Logout();' href='#'>Logout</a>");
        },
        error: function(data) {
            $("#spanUserGreeting").html("Hello <a href='#' onclick='Logout();'>unknown user</a>");
        }
    });
}

function Logout() {
    $('#linkLogout').html('Logging out...');

    $.ajax({
        type: "POST",
        url: "/services/LoginService.svc/Logout",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        data: {},
        success: function(data) {
            var user = (typeof data.d) == 'string' ? eval('(' + data.d + ')') : response.d;
            if (user.anonymous != true) 
            { 
                window.location = '/Login.aspx?ReturnUrl=%2fdefault.aspx';  
                $.cookie('EmailAddress', null); 
            }
            else alert('Could not log you out');
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {
            alert('We are sorry, but an error is preventing you from logging out.');
        }
    });
}

function InitLoginForm() {
    SwitchLoginForm($.cookie('loginAs'));
}

function ClearLoginCookie() { $.cookie('loginAs', null); }

function SwitchLoginForm(loginFormInd) {
    if (loginFormInd != true) {
        $("#loginFormTitle").html("Login as a Workgroup <span>(<a href='#' onclick='SwitchLoginForm(true);'>Switch to Individual</a>)</span>");
        $("#labelLogin").html("Workgroup Name");
        $("#labelDept").css({ "display": "block" });
        $("#txtDept").css({ "display": "block" });
        $("#imgLoginInd").css("opacity", 0.3);
        $("#imgLoginComp").css("opacity", 1.0);
        loginFormInd = false;
        $.cookie('loginAs', loginFormInd);
    }
    else {
        $("#loginFormTitle").html("Login as an Individual <span>(<a href='#' onclick='SwitchLoginForm(false);'>Switch to Workgroup</a>)</span>");
        $("#labelLogin").html("Email");
        $("#labelDept").css({ "display": "none" });
        $("#txtDept").css({ "display": "none" });
        $("#imgLoginInd").css("opacity", 1.0);
        $("#imgLoginComp").css("opacity", 0.3);

        loginFormInd = true;
        $.cookie('loginAs', loginFormInd);
    }
    $("#txtLogin").focus();
}

function Login() {
    $('#buttonLogin').toggle();
    $('#buttonClear').toggle();
    $("#divLoggingIn").toggle();
    var dataInput = JQData(["username", $('#txtLogin').val(),"password", $('#txtPassword').val()]);

    $.ajax({
        type: "POST",
        url: "/services/LoginService.svc/Login",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        data: dataInput,
        success: function(data) {
            if (data.d.anonymous != true) {
                if (jQuery.url.param("ReturnUrl") != undefined) window.location = unescape(jQuery.url.param("ReturnUrl"));
                else window.location = "/";
            }
            else {
                $("#divLoginMessage").html("We are sorry, but we could not authenticate you.  Please check your login details and try again.");
                $("#divLoginButtons").toggle();
                $("#divLoggingIn").toggle();
            }
        },
        complete: function() { $("#divLoginButtons").toggle(); $("#divLoggingIn").toggle(); },
        error: function(XMLHttpRequest, textStatus, errorThrown) {
            $("#divLoginMessage").html("We are sorry, but a system error is preventing your authentication.  Please contact Page Visions. <!-- " + textStatus + ", " + errorThrown);
        }
    });
}
