var currentAssetURL = null;

function ajaxLogin() {
    try {
        resetLoginBox();
        var action = $("#login-architect").attr("action");
        var loginData = $("#login-architect").serialize();
        $.ajax({
            type : "GET",
            url : action,
            data : loginData,
            dataType : "json",
            beforeSend: function (xhr) {
                xhr.setRequestHeader('Accept', 'application/json');
            },
            success : function(data, textStatus, XMLHttpRequest) {
                handleJSONResponse(data);
            },
            error : function(data, textStatus, XMLHttpRequest) {
                handleFailure();
            }
        });
    } catch (error) {
        handleFailure();
    }
    return false;
}

function resetLoginBox() {
    try {
        $(".notAuthenticated").hide();
        $(".notAuthorized").hide();
        $(".loginError").hide();
    } catch(error) {
    }
}

function handleJSONResponse(response) {
    try {
        if (!response.authenticated != "true") {
            notAuthenticated();
        } else if (response.authorized != "true") {
            notAuthorized();
        } else {
            authenticate();
        }
    } catch (error) {
        handleFailure();
    }
}

function handleFailure() {
    $(".loginError").show();
}

function authenticate() {
    // close login box
    if (typeof closeFancybox == 'function') {
        javascript:closeFancybox();
    }

    // open asset in new window
    openSecuredAsset();
    // refresh page this is reloading indefinetly!
    //location.reload();
}

function notAuthenticated() {
    $(".notAuthorized").show();
}

function notAuthorized() {
    $(".notAuthorized").show();
}

function openSecuredAsset() {
    if (currentAssetURL != null && currentAssetURL != "") {
        var wi = window.open(currentAssetURL, "architectasset");
        try {
            if (wi != null) {
                wi.focus;
            }
        } catch(error) {
        }
    }
}

function registerFormSubmit() {
    $("#login-architect").submit(function() {
        return false;
    });
}

function storeAssetLink(url) {
    currentAssetURL = url;
}

