/**
 * a Parser object encapsulates a text string and exposes methods
 * that operate on that text string.
 *
var p = new Parser("this is a [parser] test");
Response.Write(p.text + "<br>");
Response.Write(p.extract("[", "]", true) + "<br>");
Response.Write(p.text + "<br>");
 *
 */
function Parser(text) {
	this.text = text;
	this.setText = setText;
	this.replaceOne = replaceOne;
	this.replaceAll = replaceAll;
	this.extract = extract;
}

/**
 * sets the text in the Parser object to be the specified text
 */
function setText(text) {
	this.text = text;
}

/**
 * replaces the all instances of the specified text in the specified
 * String with the specified replacement text
 */
function replaceAll(target, replaceWith) {
	//Response.Write(target + "<BR>");
	//Response.Write(replaceWith + "<BR>");
  var pos = -1;
  var lpos = -1;
  while ( (pos = this.text.indexOf(target, lpos)) >= 0) {
    this.text = this.text.substring(0, pos) +
                replaceWith +
                this.text.substring(pos + target.length, this.text.length);
    lpos = pos + replaceWith.length;
  }
}

/**
 * replaces only the first instance of the specified text with the specified
 * replacement text
 */
function replaceOne(target, replaceWith) {
  var pos = this.text.indexOf(target);
  if (pos >= 0) {
    this.text = this.text.substring(0, pos) +
                replaceWith +
                this.text.substring(pos + target.length, this.text.length);
  }
}

/**
 * locates the left and right delimitters within the specified text
 * and returns the text between them.  if remove is true, the delimitters
 * and their enclosed text are removed from the original text
 */
function extract(left, right, remove) {
  var results = "";

  // find left delimitter
  var leftPos = this.text.indexOf(left);
  if (leftPos >= 0) {

    // find right delimitter
    var rightPos = this.text.indexOf(right, leftPos + left.length);
    if (rightPos >= 0) {

      // extract the return value
      results = this.text.substring(leftPos + left.length, rightPos);

      // remove the extracted text from the input text
      if (remove) {
        this.text = this.text.substring(0, leftPos) +
                    this.text.substring(rightPos + right.length, this.text.length);
      }
    }
  }

  // return value
  return results;
}
