﻿//-----------------------------------------------------------------------------
// XMatch
//
// Copyright 2005-2010 - Xcential Group LLC.
//
//-----------------------------------------------------------------------------

//=============================================================================
// Constructor

function XMatch(
   text,
   regExp,
   flags
)
{
   text = (text == null) ? "" : text.toString();
   flags = (flags == null) ? null : flags;
   regExp = (typeof(regExp) == "string") ? ((flags) ? new RegExp(regExp, flags) : new RegExp(regExp)) : regExp;

   var matches = text.match(regExp);

   if (matches == null)
   {
      XMatch.leftContext = "";
      XMatch.lastMatch = "";
      XMatch.rightContext = "";
      XMatch.matches = ["","","","","","","","","","",""];
   }
   else
   {
      if (RegExp.lastIndex != null && typeof(RegExp.lastIndex) == "number" && RegExp.lastIndex > 0)
         XMatch.lastIndex = RegExp.lastIndex;
      else if (regExp.lastIndex != null && typeof(regExp.lastIndex) == "number" && regExp.lastIndex > 0)
         XMatch.lastIndex = regExp.lastIndex;
      else
         XMatch.lastIndex = matches.index + matches[0].length;
      XMatch.leftContext = text.substr(0,matches.index);
      XMatch.lastMatch = text.substring(matches.index, (XMatch.lastIndex >= 0 && XMatch.lastIndex < text.length  ) ? XMatch.lastIndex : text.length);
      XMatch.rightContext = (XMatch.lastIndex >= 0) ? matches.input.substr(XMatch.lastIndex) : "";
      XMatch.matches = matches;
   }

   return (matches == null) ? 0 : matches.length;
}

XMatch.objectClass = "XMatch";

//=============================================================================
// Static Interface

XMatch.leftContext = "";
XMatch.lastMatch = "";
XMatch.rightContext = "";
XMatch.matches = ["","","","","","","","","","",""];

//=============================================================================

