/*
   Constructor.
   Split up a material string based upong the separator.

   Param    -  sentence, the String to be split up.
   Param    -  separator, the String to look for within sentence. Should be
               something like "," or ".", not a regular expression.
    
    **************************USAGE***********************************        
    var separator = ",";
   	var names = "one,two,three";

   	var tokenizer = new StringTokenizer (names, separator);

   	while (tokenizer.hasMoreTokens())
   	{
   		document.write("<p>Name " + tokenizer.nextToken() + "</p>");
   	}  

*/
function StringTokenizer (sentence, separator)
{
   // Attributes.
   this.sentence = sentence;
   this.separator = separator;

   // Operations.
   this.getTokens = getTokens;
   this.nextToken = nextToken;
   this.countTokens = countTokens;
   this.hasMoreTokens = hasMoreTokens;
   this.tokensReturned = tokensReturned;

   // Initialisation code.
   this.tokens = this.getTokens();
   this.tokensReturned = 0;

} 

function getTokens()
{
	//alert("begin get tokens");
  	// 1,2,1
   var tokens = new Array();
   var nextToken;

	if (this.sentence.indexOf (this.separator) < 0)
	{
		tokens [0] = this.sentence;
		return tokens;
	}  

   // Establish initial start and end positions of the first token.
   start = 0;
   end = this.sentence.indexOf (this.separator, start);

	//alert("begining: start " + start + " and end " + end);

   // Counter for how many tokens were found.
   var counter = 0;

   // Go through sentence, token at a time.
  // alert("sentence: " + this.sentence);
 	while (this.sentence.length - start >= 1)
	{
		nextToken = this.sentence.substring (start, end);
		//alert("1. next token " + nextToken);
		start = end + 1;
		if (this.sentence.indexOf (this.separator, start + 1) < 0)
		{
			//alert("setting end to end of sentence");
			end = this.sentence.length;
		}  
		else
		{
			end = this.sentence.indexOf (this.separator, start + 1);
		}  

		//alert("inserting token: " + nextToken);
      tokens [counter] = trim (nextToken);

		counter ++;
		//alert("counter: " + counter);
		//alert("condition: " + this.sentence.length - start + " > " + 1);
	}   // end if


	//alert("iterating through tokens, number of tokens = " + tokens.length );
	//for(var i = 0; i<tokens.length; i++){
	//	alert("token: " + tokens[i]);
	//}

   return tokens;
   
   
} 

function countTokens()
{
  return this.tokens.length;
}

function nextToken()
{

   if (this.tokensReturned >= this.tokens.length)   {
      return null;
   }    else   {
      var returnToken = this.tokens [this.tokensReturned];
      this.tokensReturned ++;
      return returnToken;
   }  

}  


function hasMoreTokens()
{
   if (this.tokensReturned < this.tokens.length)   {
      return true;
   }     else   {
      return false;
   }  
} 

function tokensReturned()
{
   return this.tokensReturned;
}  

function trim (strToTrim) {
   return(strToTrim.replace(/^\s+|\s+$/g, ''));
} 