// Regular Expression Validator


function CheckRegex( f, ptrn, txt )
{
  var pattern = f.elements[ptrn].value ;
  var source = f.elements[txt].value ;
  
  if ( pattern.length == 0 ) {
    alert( "You must enter a pattern to use." );
    return;
  }
  
  try
    {
      var matches = ExtractMatches( new RegExp( pattern, "g" ), source )
	//alert( "There were " + matches.length + " matches." ) ;
	if(matches.length == 1) {
	  str = "<font color=green>There was " + matches.length + " match.</font>";
	  for (var i=0; i<matches.length; i++)
	    {
	      str += "<br />Match " + (i+1) + ": " + matches[i].Text ;
	    }
	  document.all['result'].innerHTML=str;
	} else if(matches.length > 0) {
	  str = "<font color=green>There were " + matches.length + " matches.</font>";
	  for (var i=0; i<matches.length; i++)
	    {
	      str += "<br />Match " + (i+1) + ": " + matches[i].Text ;
	    }
	  document.all['result'].innerHTML=str;
	} else {
	  document.all['result'].innerHTML="<font color=red>There were " + matches.length + " matches.</font>";
	}
    } 
  catch ( ex )
    {
      alert( ex.message ) ;
    }
}

function CheckRegexOld( f, ptrn, txt )
{
  var pattern = f.elements[ptrn].value ;
  var source = f.elements[txt].value ;
  
  if ( pattern.length == 0 ) {
    alert( "You must enter a pattern to use." );
    return;
  }
  
  try
  {
    var matches = ExtractMatches( new RegExp( pattern, "gi" ), source )
    //alert( "There were " + matches.length + " matches." ) ;
    if(matches.length == 1) {
      document.all['result'].innerHTML="<font color=green>There was " + matches.length + " match.</font>";
    } else if(matches.length > 0) {
      document.all['result'].innerHTML="<font color=green>There were " + matches.length + " matches.</font>";
    } else {
      document.all['result'].innerHTML="<font color=red>There were " + matches.length + " matches.</font>";
    }
  } 
  catch ( ex )
  {
    alert( ex.message ) ;
  }
}


function ExtractMatches( re, text )
{
  var results = new Array() ;
  var arr = re.exec(text)
    while(arr != null)
      { 
	var match = new Match() ;
	match.Text = arr[0] ;
	
	for (var i=1; i<arr.length; i++)
	{
	  match.Groups[i-1] = arr[i] ;
	}
	
	results[results.length] = match ;
	arr = re.exec(text) ; 
      }
  return results ;
}


function Match()
{
  this.Text = null ;
  this.Groups = new Array() ;
}

function demo(r,t)
{
  document.reform.txtPattern.value=r;
  document.reform.txtSource.value=t;
}
