<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WizdomCorsProxy.aspx.cs" Inherits="GUI.Web.Base.WizdomCorsProxy" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script>            
        function reportIsReady() {
            window.parent.postMessage(JSON.stringify({ command: "WizdomCorsProxySuccess", session: "<%=Request.QueryString["sessionId"] ?? Session.SessionID%>", msLeftOnToken: <%=MillisecondsLeftOnToken%>, allWizdomRoles: [<%=AllWizdomRoles%>], rolesForCurrentUser: [<%=RolesForCurrentUser%>], upgradeInProgress: <%=UpgradeInProgress.ToString().ToLower() %>, currentUserLanguage: '<%=CurrentUserLanguage.ToLower() %>' }), "*");
        }
        reportIsReady();

        function requestSuccess(requestIndex, data, url) {
            window.parent.postMessage(JSON.stringify({
                command: "RequestSuccess",
                requestIndex: requestIndex,
                result: data,
                url: url
            }), "*");
        }
        function requestFailed(requestIndex, data, url) {
            window.parent.postMessage(JSON.stringify({
                command: data && data.status === 403 ? "TokenExpired" : "RequestFailed",
                requestIndex: requestIndex,
                result: flatten(data),
                url: url
            }), "*");
        }

        function flatten(obj) {
            var result = {};
            for (var key in obj) {
                result[key] = obj[key];
            }
            return result;
        }

        function makeRequest(message)
        {     
            var url = message.url + getQueryString(message.url);
            if (message.isExternalRequest) {
                url += "&sessionId=<%=Request.QueryString["sessionId"] ?? Session.SessionID%>";
            }

            var xhr = new XMLHttpRequest();
            xhr.open(message.method, url);
            xhr.setRequestHeader('Content-Type', 'application/json; charset=utf-8');
            xhr.setRequestHeader('sessionId', '<%=Request.QueryString["sessionId"] ?? Session.SessionID%>');
            xhr.setRequestHeader('SPProductNumber', '<%=Request.QueryString["SPProductNumber"]%>');
            xhr.onload = function () {
                if (xhr.status === 200 || xhr.status === 204) {
                    try {
                        requestSuccess(message.requestIndex, xhr.responseText ? JSON.parse(xhr.responseText) : xhr.responseText, message.url);
                    }
                    catch (e) { // Failed json parse, probably a stack trace or something similar
                        requestSuccess(message.requestIndex, xhr.responseText, message.url);                    
                    }
                }
                else {
                    requestFailed(message.requestIndex, xhr, message.url);
                }
            };
            xhr.send(JSON.stringify(message.data));
        }
        function getUrl(message){                        
            var url = message.url + getQueryString(message.url);
            requestSuccess(message.requestIndex, url);
        }
        function getQueryString(url) {
            var queryString = "";
            queryString += url.indexOf("?") > 0 ? "&" : "?";
            queryString += "SPCacheKey=<%=Request.Cookies["SPCacheKey"] ==null ? "" : Request.Cookies["SPCacheKey"].Value%>";
            queryString += "&SPLanguage=<%=Request.QueryString["SPLanguage"] %>";
            queryString += "&SPClientTag=<%=Request.QueryString["SPClientTag"]%>";
            queryString += "&userLoginName=<%=Request.QueryString["userLoginName"].Replace("\\","\\\\")%>";
            queryString += "&SPLocale=<%=Request.QueryString["SPLocale"]%>";
            return queryString;
        }
        function postMessageHandler(e) {
            try {
                var message = JSON.parse(e.data);

                if (message.method == "GETURL")
                    getUrl(message);
                else if(message.method == "PING")
                    reportIsReady();
                else
                    makeRequest(message);
            }
            catch (ex) {

            }
        }
        if (typeof window.addEventListener != 'undefined')
            window.addEventListener('message', postMessageHandler, false);
        else if (typeof window.attachEvent != 'undefined')
            window.attachEvent('onmessage', postMessageHandler);
    </script>
</head>
<body>
</body>
</html>
