// processFeeds.js
// ===============

var fieldMap = {};

function ajaxGetNewFeed() 
{
    var httpRequest;
    //log.write("Calling Ajax");

    // alert("you are in the ajaxGetNewFeed() function.  fileURL = " + fileURL );
    //create the XML request
    //
    if (window.XMLHttpRequest) 
    {                            // Mozilla, Safari, and other Browsers
        try 
        {
            httpRequest = new XMLHttpRequest();
            // alert("default XMLHTTP object instantiated");
        }
        catch(e) 
        {
            // error box will be presented below            
        }
        
        if(httpRequest.overrideMimeType) 
        {
            //httpRequest.overrideMimeType('text/xml');
        }
    }
    else if(window.ActiveXObject) 
    {                        //IE
        try 
        {
            httpRequest = new ActiveXObject("Msxml2.XMLHTTP");
            // alert("Msxml2 XMLHTTP object instantiated");
        }
        catch(e) 
        {
            try 
            {
                httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
                // alert("Microsoft XMLHTTP object instantiated");
            }
            catch(e) {}
        }
    }
            
    if (!httpRequest) 
    {
        //alert("System Error: Cannot create Ajax HttpRequest object");
        return false;
    }

    //Anonymous function to handle changed request states
    httpRequest.onreadystatechange = function()
    {
        switch(httpRequest.readyState)
        {
            case 0:            // uninitialized
                break;

            case 1:            // loading
                break;
                
            case 2:            // loaded
                break;
                
            case 3:            // interactive
                break;
                
            case 4:            // done!    
                if (httpRequest.status  == 200) 
                {
                    //log.write("Ajax readyState 4: The FEED file is now available on the client");
                    //log.write(httpRequest.responseText + "\r\n");
                    //log.write("=========================================");

                    // Processing of the FEED file starts here.
                    sendGamesToController(httpRequest.responseText, true);
                }
                else if (httpRequest.status  == 404)
                {    
                    //alert("Error: FEED file not found on Server. [error code: 404]");
                }
                else
                {
                    //alert("Ajax error received from Server. [error code: " + httpRequest.status + "]");
                }
                break;
            
            default:
                break;
        }
    }

    // force a bypass of the browser cache
    fileURL = this.PATH+"scoreboard.dat";

    // make the Ajax request
    httpRequest.open('GET', fileURL, true);
    httpRequest.send("");
}

function stripInvalidRows(feedDataArray)
{
   var feedRow;
    var newArray = new Array();

    //log.write("The feedDataArray has a length of " + feedDataArray.length + " (includes MAP rows and Data rows)");

    for (i = 0; i < feedDataArray.length; i++)
    {
        feedRow = trimString(feedDataArray[i]);

        if (feedRow.indexOf("|") > -1) 
        {
            newArray[newArray.length] = feedRow;
        }
    }
    return newArray;
}


function processMappingRows(feedDataArray)
{
    var feedRow;
    var indexStartOfGameData = 0;        // important to initialize

    //log.write("The feedDataArray has a length of " + feedDataArray.length + " (includes MAP rows and Data rows)");
        
    for (i = 0; i < feedDataArray.length; i++)
    {
        feedRow = trimString(feedDataArray[i]);

        if (indexStartOfGameData == 0)
            indexStartOfGameData = i;

        if (feedRow.length == 0) 
        {            
            //log.write("[processing feedDataArray] Removing extra row of empty data at position " + i);
            feedDataArray.splice(i);
        }
    }

    //log.write("[processing feedDataArray] Game data started at row " + indexStartOfGameData);

    if (isValidfieldMap() == false) 
    {
        // Doing nothing with this Failed validation right now.   This validation result is not important
        // (it's a problem with associative arrays)
        
        //log.write("Warning [very low severity]: the Master Feed File did not have valid MAP entries that described the data fields");
    }        
    // return the array index of the first row where the game data started
    return indexStartOfGameData;
}

function isValidfieldMap() {

    var fieldPosition;
    var passValidation = true;
    var key;

    for(key in fieldMap) {
    
        // the map contains array positions, so we use that variable name
        fieldPosition = fieldMap[key];

        // //log.write("inside first loop   " + key + "---->" + fieldMap[key]);


        if (fieldPosition == 'undefined') {
            //log.write("*** undefined map entry found");
            passValidation = false;
            break;            
        }

        // Each value in the map was already converted to a number (attempted conversion)
        // before it was added to the map.   We test the result of the conversion here.
        //
        // *************** use utility function **************************************
        
        if (isNaN(fieldPosition) == true) {
            //log.write("*** isNaN map entry found");
            passValidation = false;
            break;            
        }
        
        // --------------------------------------------------------------------------------
        // OPTIONAL - Can add a test to verify that there is only one ZERO value in the map,
        //                or any other test.
    }
    
    
    //log.write("---------------------------");
    //log.write("dump of all properties in the fieldMap object:");
    
    for(key in fieldMap) {
      //log.write(key + "---->" + fieldMap[key]);
    }
    
    //log.write("isValidfieldMap() Validation function returning " + passValidation);
    
    return passValidation;
}
    

function lookupFieldPosition(fieldIdentifier) {

    return fieldMap[fieldIdentifier];
}

function processMetaData(metaStr)
{
    var metaArray;
    metaArray = metaStr.split(TOP_LEVEL_DELIMITER);
    var newTimestamp = metaArray[TIMESTAMP];
    var newInterval = metaArray[SETINTERVAL];

    if (parseInt(newInterval) != parseInt(INTERVAL))
    {
        setupPollingTimer(newInterval);
        INTERVAL = newInterval;
    }

    if (parseInt(newTimestamp) > parseInt(currTimestamp))
    {
        currTimestamp = newTimestamp;
        return true;
    }
    else
        return false;
}

 
