﻿
$(document).ready(function() {

    $('a').click(function() {

        //if (this.href.indexOf('?') > 0) {

        var idx = this.href.indexOf('?');
        if (this.href.indexOf('login=1') > idx) {
            $('#protectedLink').val(this.href);
        }
        else {
            $('#protectedLink').val('');
        }

        // show modal only if not logged yet
        if ($('#isLogged').val() != 'true' && $('#protectedLink').val().length > 0)
        { $('#modalPopup').modal(); return false; }
    });
});

// event handler for 'Login' link
function LoginClient(a) {
    if ($(a).text().toLowerCase() === 'login') { $('#modalPopup').modal(); return false; }
}

// event handler for 'Logout' link
function LogoutUser() {

    $.ajax({
        type: "POST",
        //url: "http://agents.titan.local/SignIn.aspx/Logout",
        url: "../../SignIn.aspx/Logout",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(msg) {
            if (msg.d === 'OK') {
                window.location.href = '../../';
            }
        }
    });
}


// client event handler for a login button in overlay 
function LoginUser() {

    $('#loginValidator').html('');
    $('#passwValidator').html('');

    var user = $('#uname').val();
    var pass = $('#upass').val();

    if (user.length == 0) {
        $('#loginValidator').html('Please enter username');
    }
    if (pass.length == 0) {
        $('#passwValidator').html('Please enter password');
    }

    if (user.length > 0 && pass.length > 0) {

        $.ajax({
            type: "POST",
            url: "http://" + window.location.hostname + "/SignIn.aspx/SendName",
            data: "{'login':'" + user + "','passw':'" + pass + "'}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (msg) {
                if (msg.d === 'OK') {
                    $('#loginButton').attr("disabled", true);

                    if ($('#flag').val() === 'drop') {
                        window.location.href = '../../';
                        return;
                    }

                    var redirect = $('#protectedLink').val();

                    if (redirect.length > 0) {
                        //alert(redirect.replace("&login=1", ""));
                        window.location.href = redirect.replace("&login=1", "");
                    }
                    else { location.reload(); }
                }
                else if (msg.d === 'FAIL') {

                    $('#loginValidator').html('Invalid username / password');
                }
            }
        });
    }
}
