/**
 * Helper class for use in parsing JSON in the java environment.
 * @export
 */
var DvtJsonParser = {};

/**
 * Parses the input string into a JSON object and returns.
 * @return {Object}
 * @export
 */
DvtJsonParser.parse = function(str) {
  if (!str)
    return null;

  // First trim any whitespace
  str = dvt.StringUtils.trim(str);

  var firstChar = str.charAt(0);
  if (firstChar == '[' || firstChar == '{') {
    // Array or Map
    // Count the number of open/close arrays or objects
    var numOpen = 0;

    // Quote handling: Count the number of open single/double quotes, except when there is an
    // open one already.  This handles nested single quotes in double quotes, and vice versa.
    var numSingleQuotes = 0;
    var numDoubleQuotes = 0;

    // Iterate through and split by pieces
    var prevIndex = 1;
    var parts = [];
    for (var i = 1; i < str.length - 1; i++) {
      var iChar = str.charAt(i);
      if (iChar == '[' || iChar == '{')
        numOpen++;
      else if (iChar == ']' || iChar == '}')
        numOpen--;
      else if (iChar == "'" && numDoubleQuotes % 2 == 0)
        numSingleQuotes++;
      else if (iChar == '"' && numSingleQuotes % 2 == 0)
        numDoubleQuotes++;

      // If split index, store the substring
      if (numOpen == 0 && (numSingleQuotes % 2 == 0 && numDoubleQuotes % 2 == 0) && iChar == ',') {
        parts.push(str.substring(prevIndex, i));
        prevIndex = i + 1;
      }
    }

    // Grab the last part if present
    if (prevIndex < str.length - 1)
      parts.push(str.substring(prevIndex, str.length - 1));

    // Decode the parts into the result
    var ret;
    if (firstChar == '[') {
      ret = [];
      for (var arrayIndex = 0; arrayIndex < parts.length; arrayIndex++)
        ret.push(DvtJsonParser.parse(parts[arrayIndex]));
    }
    else if (firstChar == '{') {
      ret = {
      };
      for (var mapIndex = 0; mapIndex < parts.length; mapIndex++) {
        var mapPart = parts[mapIndex];
        var colonIndex = mapPart.indexOf(':');
        var mapKey = mapPart.substring(1, colonIndex - 1); // 1 to -1 to avoid the quotes
        var mapValue = DvtJsonParser.parse(mapPart.substring(colonIndex + 1, mapPart.length));
        ret[mapKey] = mapValue;
      }
    }
    return ret;
  }
  else if (firstChar == '"')// String
    return str.substring(1, str.length - 1);
  else if (str == 'true')
    return true;
  else if (str == 'false')
    return false;
  else if (str == 'null')
    return null;
  else if (dvt.Agent.isEnvironmentTest() && str.substring(0, 5) == 'eval(') {//@HtmlUpdateOK
    // Supports JsonUtils.Verbatim.  Only used for testing.
    //Only used in testing environment @HtmlUpdateOK
    //BUG 34184877 - MAKE DVT COMPATIBLE WITH CSP STANDARDS
    var func = window;
    var funcSplit = str.substring(5, str.length - 3).split('.');
    for(i = 0;i < funcSplit.length;i++)
    {
      func = func[funcSplit[i]];
    } 
    return func();
  }
  else
    return Number(str);
};
