/**
 * @license Copyright (c) Microsoft Corporation. All rights reserved.
 */

var Helper = {};

Helper.hashToObject = function (hash) {
    var _removeHash = function (input) {
        if (input.indexOf("#/") > -1) {
            input = input.substring(input.indexOf("#/") + 2);
        } else if (input.indexOf("#") > -1) {
            input = input.substring(1);
        }

        return input;
    };

    var _deserialize = function (input) {
        var match,
            pl = /\+/g,  // Regex for replacing addition symbol with a space
            search = /([^&=]+)=?([^&]*)/g,
            decode = function (s)
            {
                return decodeURIComponent(s.replace(pl, " "));
            },
            obj = {};
        match = search.exec(input);
        
        while (match) {
            obj[decode(match[1])] = decode(match[2]);
            match = search.exec(input);
        }

        return obj;
    };

    return _deserialize(_removeHash(hash));
};

Helper.getAuthority = function (redirectUri) {
    return "https://login.microsoftonline.com/";
};

Helper.isIEorEdge = function () {
    var ua = navigator.userAgent.toLowerCase();
    if (ua && (ua.indexOf("msie") !== -1 || ua.indexOf("trident") !== -1 || ua.indexOf("edge") !== -1))
        return true;

    return false;
}

Helper.navigateToUrl = function (url) {
  var timeout = Helper.isIEorEdge() ? 500 : 0;

  setTimeout(function () {
    window.location.assign(url);
  }, timeout);
};

Helper.toSimpleTypeValue = function(value)  {
	if (typeof value === "string" || typeof value === "number" || typeof value === "boolean")
		return value;

	if (value instanceof Date)
		return value.toISOString();

	return JSON.stringify(value);
}

Helper.errorToObject = function(error) {
    var obj = {};

    // Skip handling non-object type errors and arrays
    if (typeof error !== "object" || Array.isArray(error))
        return error;

    if (!error) {
        obj.error = "undefined";
    } else {
        var ownProps = Object.getOwnPropertyNames(error);
        
        for (var i = 0, len = ownProps.length; i < len; i++) {
            var key = ownProps[i];
            obj[key] = error[key];
        }
    }

    return obj;
}