﻿
/***********************************************************
    TAB DELIMITED TEXT PARSER
*************************************************************/

var FieldsArray =new Array();//field names
var m_dataSet= new Array();//the datasetvar ;

function SetDelimitedString( strTab )
{  
    var delimitorFieldContent = "==" ;
    var delimitorContentSTATS = "===" ;

    var data = strTab.substring(strTab.indexOf(delimitorFieldContent)+4,strTab.indexOf(delimitorContentSTATS)-1);
    var lines = data.split('\n');
 
    var fieldsList =strTab.slice(strTab.indexOf("\r\n=\r\n")+5,strTab.indexOf("\r\n==\r\n"));//field list
   
    FieldsArray = fieldsList.split('\t');
    
    var iDataLine = 0;
    for(var iLine=0; iLine<lines.length;iLine++)//for each line
    {
        
	    var thisLine = trim(lines[iLine]);//alert(thisLine.length);
	    if(thisLine.length>0)
	    {
			var recordSet=new Array();        
			var record = new Array();
			record = thisLine.split('\t');
	    
			if (FieldsArray.length != record.length)
			{
			    //alert("Bad record " +iLine + " # fields: "  + record.length+" There should be :"+FieldsArray.length);
			}
			else
			{	    
				for(var iRecord=0;iRecord<FieldsArray.length;iRecord++)// for each field in line
				{   
				    var field = trim(FieldsArray[iRecord].toLowerCase());
				   
				    if ( iRecord > record.length )
				    {
				        recordSet[field] ="";
				    }
				    else
				    {
				        recordSet[field]= record[iRecord];	  			    
				    }
				    
				}
	        	m_dataSet[iDataLine]=recordSet;
				iDataLine++;
			}
	    }
	    
    }
}

//this function returns all the field names
function GetFields()
{
    return FieldsArray;
}

//this function returns the fieldname when the index is given
function GetFieldName(index)
{
    return FieldsArray[index];
}
//this function returns the index when the filed name is given
function GetFieldIndex(fieldName)
{
    for(var i=0;i<FieldsArray.length;i++)
    {   
        if (trim(FieldsArray[i].toLowerCase())==trim(fieldName.toLowerCase()) )
        {
            return i;            
        }        
    }
}
//this funnction returns the dataset
function GetDataSet()
{
    return m_dataSet;
}
//this funnction returns the number of records in the dataset
function GetRecordNumber()
{
    return m_dataSet.length;
}
//this function returns the whole record when the index is given
function GetRecord(index)
{
    return m_dataSet[index];
}
//this function trims a given string
function trim(str)
{
	var	str = str.replace(/^\s\s*/, ''),
	    ws = /\s/,
	    i = str.length;
	while (ws.test(str.charAt(--i)));
	return str.slice(0, i + 1);
}