//////////////////////////////////////////////////////////
//
//  Network Performance Gadget
//  Created by Jerry Berg on 6/12/06 6:21pm
//  Enjoy!
//
//  DO NOT MODIFY AND REDISTRIBUTE
//
//////////////////////////////////////////////////////////

//
//  Globals
//
var server = GetObject( "winmgmts:" ); 
var refresher = new ActiveXObject("WbemScripting.SWbemRefresher");
var items = refresher.AddEnum( server, "Win32_PerfFormattedData_Tcpip_NetworkInterface").ObjectSet;
var maxSpeed = 0;

//
//  Initialize and start worker psudo thread
//
function Start()
{
   System.Gadget.settingsUI = "Settings.html";

   RX.innerText = "";
   TX.innerText = "";
   WorkerThread();
}

//
//  Where all the magic happens
//
function WorkerThread() 
{
    // Set network card name
    NetworkCardName.innerText = System.Gadget.Settings.read("selectedItem");

    // Refresh WMI collection
    refresher.Refresh();
    
    // Get enumator from WMI item collection
    var e = new Enumerator( items );
    
    for(; !e.atEnd(); e.moveNext() )
    {
        // If user has not selected a network card default to the first one
        if( NetworkCardName.innerText == "" )
        {
            NetworkCardName.innerText = e.item().Name;
        }
    
        // Update data for currently selected network card
        if( e.item().Name == NetworkCardName.innerText )
        {
            // Compute input/output speeds in KB per second
            var inSpeed  = Math.round( e.item().BytesReceivedPersec / 1024 );
            var outSpeed = Math.round( e.item().BytesSentPersec / 1024 )
            
            // Push up the max speed bar if new record is acheived
            if( inSpeed > maxSpeed ) maxSpeed = inSpeed;
            if( outSpeed > maxSpeed ) maxSpeed = outSpeed;
            
            // Set text to MB or KB depending on value
            RX.innerText = (inSpeed  > 1024 ? ( Math.round( inSpeed / 1024 )  + " MB" ) : inSpeed  + " KB");
            TX.innerText = (outSpeed > 1024 ? ( Math.round( outSpeed / 1024 ) + " MB" ) : outSpeed + " KB");
            
            // Set the colored bar to the correct width based on current speed vr. max speed
            RXBar.style.width = (inSpeed == 0 && maxSpeed == 0) ? "0%" : ((inSpeed / maxSpeed)  * 100 + "%");
            TXBar.style.width = (outSpeed == 0 && maxSpeed == 0) ? "0%" : ((outSpeed / maxSpeed) * 100 + "%");
        }
    }	
    
    // Call us again
    if( System.Gadget.Settings.read("intervalItem") == "" )
    {
        setTimeout("WorkerThread()", 1000);
    } else {
        setTimeout("WorkerThread()", System.Gadget.Settings.read("intervalItem"));
    }
}

