﻿
//TODO: check for group cookies, if not setted, set the cookie based on ajax call to proxy.aspx.
// then redirect if needed

var groupRedirectCookie = 'svsgroups#' + getUName();
var usergroups = getCookie(groupRedirectCookie);
var cookieExpireDays = 1;
if (getUName() != '') {
    if (usergroups != null && usergroups != '' && usergroups != 'undefined') {
        // we have cookie setted, we do parse the value and do the redirect
        doRedirect(usergroups);
    }
    else {
        // we don't have the cookie, we need to call proxy.aspx and get the updated values for 
        // current user, then do the redirect
        $.get("/proxy.aspx?command=grouppagesredirect", function (result) {
            if (result == '') return;
            var jsonResult = eval('(' + result + ')');
            cookieExpireDays = jsonResult.CookieExpireTime;
            setCookie(groupRedirectCookie, result, cookieExpireDays);
            doRedirect(result);
        });
    }
}

function doRedirect(usergroups) {
    var currentURL = window.location;
    var oResultData = eval('(' + usergroups + ')');
    var redirectTo = '';
    var currentUser = getUName();
    if (currentUser != oResultData.UserName) return;
    //here we must parse the structure
    for (var j in oResultData.GroupRedirs) {
        var groupRedir = oResultData.GroupRedirs[j];
        for (var i in groupRedir.PageRedirects) {
            //here we parse every page
            var pageRedir = groupRedir.PageRedirects[i];
            var sourceAbsoluteURL = getBaseURL() + pageRedir.SourceURL;
            if (sourceAbsoluteURL.toLowerCase() == currentURL.toString().toLowerCase()) {
                redirectTo = getBaseURL() + pageRedir.TargetURL; //TargetURL should be relative in Sitecore

                //finnaly do the redirect on first match.
                window.location = redirectTo;
                break;
            }
        }
    }
}

function getBaseURL() {
    //gets the current domain.
    var url = location.protocol + '//' + location.host;
    return url;
}
