﻿$(document).ready(function () {    
    $("a[href*='localhost/cs'], a[href*='localhost/ngc'], a[href*='localhost/pmg'], a[href*='www.collectors-society.com'], a[href*='ngccoin.com'], a[href*='cgccomics.com'], a[href*='pmgnotes.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);
            $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('Original :' + originalURL);
                DebugOutput('Service url :' + location.protocol + "//" + location.host + AutoLoginConfig.contextPath + "TokenService.asmx/GetTokenUrl");

                $.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);
        }
    }
});
