﻿
var Tina = {

    onloginCallback: null,
    successUrl: null,
    refreshPage: false,

    openLoginWindow: function (json) {

        document.domain = this.getDomain();

        this.successUrl = json.successUrl ? json.successUrl : "";
        this.onloginCallback = json.onLogin ? { "method": json.onLogin, "scope": json.scope} : null;
        this.refreshPage = json.refreshPage ? json.refreshPage : false;

        // popup dimensions
        var settings = this.buildSettings(json);

        // store old RapUserId in session cookie (to be used for migration)
        if (json.oldRapId) {
            document.cookie = "oldRapId=" + json.oldRapId;
        }

        // open window
        window.open(settings[0], 'login', settings[1]);
    },

    buildSettings: function (json) {
        var width = 800;
        var height = 500;
        var template = json.template ? "?t=" + json.template : ""; ;
        var loginWindowUrl = json.tinaBaseUrl;

        switch (json.loginProvider) {
            case "Facebook":
                loginWindowUrl += "/Provider/FacebookOAuth.aspx";
                break;
            default:
                loginWindowUrl += "/LoginWindow.aspx";
                break;
        }

        loginWindowUrl += template;

        var params = "height=" + height;
        params += ",width=" + width;
        params += ",top=" + (screen.height - height) / 2;
        params += ",left=" + (screen.width - width) / 2;

        return [loginWindowUrl, params];
    },


    loginCallback: function (json) {
        //json: "{ authenticated: {0}, dn: '{1}', avatarUrl: '{2}', userId: '{3}', profileUrl: '{4}', profileType: '{5}'}"

        if (this.onloginCallback != null) {

            if (typeof (this.onloginCallback.method) === "function") {
                this.onloginCallback.method(json, this.onloginCallback.scope);
            }
        }
        else {
            if (this.refreshPage == true) {
                setTimeout('window.location.reload()',200);
            }
            else if (this.ExistsAndNotEmpty(this.successUrl)) {
                window.location = this.successUrl;
            }
        }
    },

    getDomain: function () {
        var parts = window.location.hostname.split('.');
        var lastPart = parts[parts.length - 1];
        var partCount = 2; // com, net, org
        if (lastPart !== "com" && lastPart !== "net" && lastPart !== "org") {
            partCount = 3;
        }

        var domain = [];
        for (var i = 0; i < partCount; i++) {
            domain.push(parts[parts.length - (i + 1)]);
        }

        return domain.reverse().join(".");
    },

    ExistsAndNotEmpty: function (prop) {
        return (typeof (prop) != "undefined" && prop.length > 0);
    },

    switchProvider: function (provider) {
        window.location = "Provider/" + provider + "OAuth.aspx";
    }


};


