var orgUrl = 'https://cliffordchance-dev.oktapreview.com'; // Overridden in Config template
var str = decodeURIComponent(window.location.href);
var redirectUrl = 'https://cliffordchance-dev.oktapreview.com/home/cliffordchancesandbox_aemoktauatpublish_1/0oa3w8v33nlKiHnIq0x6/aln3wb85jzsix7dBi0x6'; // Overridden in Config template
var oktaCCLogin = ''; // Overridden in Config template

var oktaSignIn;

$(document).ready( function() {

    if ($('div#okta-login-container').length > 0) {

        orgUrl = $('section#section_tkosp').data('oktaorgurl');
        redirectUrl = $('section#section_tkosp').data('oktaredirecturl');
        oktaCCLogin = $('section#section_tkosp').data('oktacclogin');
    
        // Standard Okta Sign-in Widget
        // -------------------------------------------------------------
    
        oktaSignIn = new OktaSignIn(
            {
                baseUrl: orgUrl, 
                features: { 
                    registration: true,
                    selfServiceUnlock: true
                },
                language: 'en',
                i18n: {
                    'en': {
                        'socialauth.divider.text': ' ',
                        'errors.E0000004' : 'Username/Password not recognised, please register for the Client Portal below if you haven\'t already'
                    }
                },
                helpLinks: {
    				help: 'https://www.yongaandsimiyu.com/help.html'
  				},
                customButtons: [
					{
                        title: 'Clifford Chance Sign-in',
                        click: function() {
                            window.location.href = oktaCCLogin;
                        }
                    }
                ]

            }
    
        );
    
        oktaSignIn.renderEl({ el: '#okta-login-container' },
            function (res) {
                if (res.status === 'SUCCESS') {
                    console.log('User %s successfully authenticated %o', res.user.profile.login, res.user);
                    res.session.setCookieAndRedirect(redirectUrl);
                    /*
                    if (str.includes("?fromURI")) {
                        res.session.setCookieAndRedirect(redirectUrl);
                    } else {
                        res.session.setCookieAndRedirect(orgUrl);
                    }
                    */
                }
            }
        );

        // oktaSignIn.hide();
    
    
        // ================================ START: CLICK FUNCTIONS ================================ //
    
        // Give test cookie buttons click functions
        $('section#section_tkosp').on('click', 'a#a_logout', function(e) {
            logOutOfOkta();
            e.preventDefault();
        });

        $('div#okta-login-container').on('click', 'a.registration-link', function(e) {
            registrationInitiate(cc_aa_js_pagename + '|oktalogin|Sign Up|n/a|Registration|Clicked Log-in on Okta Login form');
            extendTKOSP();
            e.preventDefault();
        });
    
        $('div#okta-login-container').on('click', 'div.registration a.link', function(e) {
            extendTKOSP();
            e.preventDefault();
        });
    
        $('div#okta-login-container').on('click', 'a.js-forgot-password, a.js-back', function(e) {
            fadeOktaForm();
            e.preventDefault();
        });

        $('div#okta-login-container').on('mousedown touchstart', 'a.btn-customAuth', function(e) {
            constructSamlRedirect(true);
            e.preventDefault();
        });
    
        $('div#okta-login-container').on('click', 'input[type=submit]', function(e) {

            if ($(this).attr('id') == 'okta-signin-submit') {
				constructSamlRedirect(true);
                loginInitiate(cc_aa_js_pagename + '|oktalogin|Sign In|n/a|Login|Clicked Sign In on Okta Login form');
            } else {
                evalRegForm();
                fadeOktaForm();
            }

        });

        /* Save for header rework (summer/autumn 2020) */

        $('section#section_cp_marquee_info').on('click', 'a.a_marquee_register', function(e) {
            $('a#a_tkosp_button').trigger('click');
            $('a#a_tkosp_button').trigger('focus');
            let signup = document.getElementsByClassName('registration-link');
            if (signup.length > 0) {
        		signup[0].click();
            }
            e.preventDefault();
        });

    }

	// Call SAML Redirect function at any time to check if we need to log URL in query strings
	// constructSamlRedirect(false);

});

// ============================== START: OKTA LOGIN FUNCTIONS ============================ //

function extendTKOSP() {

    var nV1 = 400;
    var nV2 = 600;

	fadeOktaForm();

    if ($('section#section_tkosp').height() == nV1) {
		$('section#section_tkosp').animate({'height': nV2 + 'px'}).css({'overflow': 'visible'});
        $('ul#ul_tkosp_toolkits_list').animate({'height': (nV2 - parseInt($('ul#ul_tkosp_toolkits_list').css('padding-top'))) + 'px'}).css({'overflow': 'visible'});
        $('#div_fixed_header').animate({'margin-top': nV2 + 'px'});
        $('h2#h2_tkosp_button').animate({'top': nV2 + 'px'});
        $('section#section_tkosp').attr('data-maxheight', nV2);
		$('#okta-login-container').animate({'height' : nV2 - 40 + 'px'}); 
	} else {
		$('section#section_tkosp').animate({'height': nV1 + 'px'}).css({'overflow': 'visible'});
        $('ul#ul_tkosp_toolkits_list').animate({'height': (nV1 - parseInt($('ul#ul_tkosp_toolkits_list').css('padding-top'))) + 'px'}).css({'overflow': 'visible'});
        $('#div_fixed_header').animate({'margin-top': nV1 + 'px'});
        $('h2#h2_tkosp_button').animate({'top': nV1 + 'px'});
        $('section#section_tkosp').attr('data-maxheight', nV1);
		$('#okta-login-container').animate({'height' : nV1 - 40 + 'px'}); 
	}

}

function fadeOktaForm() {
	$('div#okta-login-container').animate({
        'opacity': '0'
    }, 90, function() { 
		$('div#okta-login-container').delay(100).animate({'opacity': '1'});
    });
}

function logOutOfOkta() {
    $.ajax({
	    url: '/cc/logout',
	    type: 'Post',
	    data: {},
        success: function (res) {
            localStorage.setItem("Customer_logout", true);
			document.cookie = "oktauser" + "=; Path=/; Expires=Thu, 01 Jan 1970 00:00:01 GMT;";
            document.cookie = "cc_bookmarks" + "=; Path=/; Expires=Thu, 01 Jan 1970 00:00:01 GMT;";
            document.cookie = "cc_checkedCookie" + "=; Path=/; Expires=Thu, 01 Jan 1970 00:00:01 GMT;";
            //signOutUser();
			alert('You have been logged out. Click OK to refresh the page.');
oktaSignIn.authClient.signOut().then(function() {

   console.log('Session closed successfully');

         // document.body.innerHTML += '<div>You have been logged out. Click OK to refresh the page.</div>'
      //alert('You have been logged out. Click OK to refresh the page.');
	  //location.reload(true);
          // 100 milliseconds delay
 })
.catch(function(err) {
console.error('Error closing session:', err);
 });


		},
		error: function (err) {
			alert('Could not log-out of AEM: ' + err);
		}
	});
}

function evalRegForm() {
    console.log('evalRegForm()');
    console.log('PRECONDITION: ' + $('div#subschemas-password').find('div.subschema-error').length + ' | ' + $('div.registration').find('p.o-form-input-error').length);
    // Loop over the inputs and sequentially focus them to trigger errors (if any) before we try to submit
    $('div.okta-login-container').find('input[type=text]').each( function() {
		$(this).focus().blur();
    });
    if ($('div#subschemas-password').find('div.subschema-error').length == 0 && $('div#subschemas-password').find('div.subschema-unsatisfied').length == 0 && $('div.registration').find('p.o-form-input-error').length == 0) {
        console.log('POSTCONDITION: ' + $('div#subschemas-password').find('div.subschema-error').length + ' | ' + $('div.registration').find('p.o-form-input-error').length);
        registrationStatus();
    }
}

function constructSamlRedirect(bFromLoginClick) {
    console.log('constructSamlRedirect: 1 - ' + bFromLoginClick);
	// Check if a saml_request_path is already present and only override if it isn't
    if (!!$.cookie('saml_request_path')) {
		// Do less
        console.log('constructSamlRedirect: 2');
    } else {
        var aQueryString = getParams(window.location.href);
        $.cookie.raw = true;
		console.log('constructSamlRedirect: 3');

        // if (!bFromLoginClick) {
        console.log('constructSamlRedirect: 4');
        if (aQueryString['referrerloggedout'] != undefined) {
            $.cookie('cc_saml_request_path', aQueryString['referrerloggedout'], { path: '/' });
        } else if (aQueryString['referrerloggedin'] != undefined) {
            console.log('constructSamlRedirect: 5');
            $.cookie('cc_saml_request_path', aQueryString['referrerloggedin'], { path: '/' });
        } else {
            $.cookie('saml_request_path', '/client-portal.html', { path: '/' });
            console.log('constructSamlRedirect: 6');
        }
       	// } else if (bFromLoginClick) {
        	// $.cookie('saml_request_path', '/client-portal.html', { path: '/' });
            // console.log('constructSamlRedirect: 7');
        // }

    }
}

function executeSamlRedirect() {
    console.log('executeSamlRedirect: 1');
	if (!!$.cookie('cc_saml_request_path')) {
        console.log('executeSamlRedirect: 2');
        var sRedirectLocation = $.cookie('cc_saml_request_path');
        $.removeCookie('cc_saml_request_path', { path: '/' });
		window.location.replace(sRedirectLocation);
    }
}

