﻿$(document).ready(function () {
    $("a[href*='localhost/cs'], a[href*='localhost/ncs'], a[href*='localhost/pmg'], a[href*='collectors-society.com'], a[href*='cgccomics.com'], a[href*='pmgnotes.com'], a[href*='ncscoin.com']")
    .not("a[href*='boards.collectors-society.com']").click(function (e) {
        if (AutoLoginConfig.FeatureIsOn == 'true') {
            DebugOutput('Context Path ' + AutoLoginConfig.contextPath);
            DebugOutput('Display Debug ' + AutoLoginConfig.DisplayDebug);
            DebugOutput('Feature is On ' + AutoLoginConfig.FeatureIsOn);
            $target = $(e.target);
            DebugOutput('First :' + $target);

            var cnt = 0;
            while (cnt < 10 && $target != null && !$target.is('a')) {
                DebugOutput(cnt + '->' + $target);
                $target = $target.parent();
                cnt = cnt + 1;
            }

            DebugOutput('Last :' + $target.get(0));
            DebugOutput('href :' + $target.is('a'));
            DebugOutput('Null Check :' + ($target != null));

            if ($target != null && $target.is('a')) {
                var originalURL = $target.get(0);
                DebugOutput('Target :' + ($target.attr("target")));
                DebugOutput('URL :' + ($target.attr("href")));

                DebugOutput(originalURL);

                $.ajax({
                    type: "POST",
                    url: location.protocol + "//" + location.host + AutoLoginConfig.contextPath + "TokenService.asmx/GetTokenUrl",
                    data: "{'destinationURL': '" + originalURL + "'}",
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    async: false,
                    success: function (returnURL) {

                        DebugOutput('success : ' + returnURL.d);
                        $target.attr("href", returnURL.d);
                        DebugOutput('New URL :' + ($target.attr("href")));
                        return true;

                    },
                    error: function (xhr, ajaxOptions, thrownError) {

                        DebugOutput(xhr);
                        DebugOutput(xhr.statustext);
                        DebugOutput(thrownError);
                        DebugOutput('fail');
                        return true;
                    }
                });
            }
            return true;
        } //end if 
    });

    function DebugOutput(msg) {
        if (AutoLoginConfig.DisplayDebug == 'true' && msg != null) {
            alert(msg);
        }
    }
});
