#include "raconfigui.h"
#include "addprofiledlg.h"
#include "authsecudlg.h"
#include "hiddenssiddlg.h"
#include "rt_tool.h"
#include "configapi.h"

#include <qvariant.h>
#include <qapplication.h>
#include <qbuttongroup.h>
#include <qcheckbox.h>
#include <qcombobox.h>
#include <qheader.h>
#include <qlabel.h>
#include <qlineedit.h>
#include <qlistview.h>
#include <qprogressbar.h>
#include <qpushbutton.h>
#include <qtabwidget.h>
#include <qwidget.h>
#include <qmime.h>
#include <qdragobject.h>
#include <qlayout.h>
#include <qtooltip.h>
#include <qwhatsthis.h>
#include <qimage.h>
#include <qpixmap.h>
#include <qmessagebox.h>
#include <unistd.h>
#include <errno.h>

PAIR_CHANNEL_FREQ_ENTRY ChannelFreqTable[] = 
{
    // channel Frequency
    {1,     2412000},
    {2,     2417000},
    {3,     2422000},
    {4,     2427000},
    {5,     2432000},
    {6,     2437000},
    {7,     2442000},
    {8,     2447000},
    {9,     2452000},
    {10,    2457000},
    {11,    2462000},
    {12,    2467000},
    {13,    2472000},
    {14,    2484000},
    {34,    5170000},
    {36,    5180000},
    {38,    5190000},
    {40,    5200000},
    {42,    5210000},
    {44,    5220000},
    {46,    5230000},
    {48,    5240000},
    {52,    5260000},
    {56,    5280000},
    {60,    5300000},
    {64,    5320000},
    {100,   5500000},
    {104,   5520000},
    {108,   5540000},
    {112,   5560000},
    {116,   5580000},
    {120,   5600000},
    {124,   5620000},
    {128,   5640000},
    {132,   5660000},
    {136,   5680000},
    {140,   5700000},
    {149,   5745000},
    {153,   5765000},
    {157,   5785000},
    {161,   5805000},
};

int G_nChanFreqCount = sizeof (ChannelFreqTable) / sizeof(PAIR_CHANNEL_FREQ_ENTRY);

const char *strAryNetworkType[]=
{
    "Ad Hoc",
    "Infrastructure", 
    "Automatic"
};

const char *strAryEncryption[]=
{
    "WEP",
    "Not Use",
    "",
    "",
    "TKIP",
    "",
    "AES",
    ""
};

const char *strAryAuthenType[]=
{
    "OPEN",
    "SHARED"
    "",
    "WPA",
    "WPAPSK",
    "WPA-None"
};


extern UINT             G_nCountryRegion;
bool                    G_bRadio = TRUE;
extern bool             G_bUserAdmin;
extern bool             G_bSupportAMode;
RT_802_11_PHY_MODE      G_enumWirelessMode = PHY_11BG_MIXED; // Default use BG_Mixed


static QPixmap uic_load_pixmap_RaConfigForm( const QString &name )
{
    const QMimeSource *m = QMimeSourceFactory::defaultFactory()->data( name );
    if ( !m )
        return QPixmap();
    QPixmap pix;
    QImageDrag::decode( m, pix );
    return pix;
}
/* 
 *  Constructs a RaConfigForm which is a child of 'parent', with the 
 *  name 'name' and widget flags set to 'f'.
 */
RaConfigForm::RaConfigForm(  int socket_id, const char *device_name, QWidget* parent,  const char* name)
    : QWidget( parent, name)
{
    if ( !name )
        setName( "RaConfigForm" );
    resize( 600, 480 ); 
    setMinimumSize( 600, 480 ); 
    setMaximumSize( 600, 480 ); 
    setCaption("Configuration Utility - RT2500");
    setIcon( uic_load_pixmap_RaConfigForm( "RaConfig2500.xpm" ) );
    setPaletteBackgroundColor( QColor( 222, 222,  222 ) );
    qApp->setStyle("Windows");

    TabWidgetRaConfig = new QTabWidget( this, "TabWidgetRaConfig" );
    TabWidgetRaConfig->setGeometry( QRect( 10, 10, 580, 460 ) );
    setPaletteBackgroundColor( QColor( 222, 222,  222 ) );
    TabWidgetRaConfig->setPaletteBackgroundColor( QColor( 222, 222,  222 ) );    
//===============================================================================
//Profile Page
//===============================================================================
    ProfilePage_tab = new QWidget( TabWidgetRaConfig, "ProfilePage_tab" );

    Profile_ButtonGroup = new QButtonGroup( ProfilePage_tab, "Profile_ButtonGroup" );
    Profile_ButtonGroup->setGeometry( QRect( 10, 10, 550, 410 ) ); 
    Profile_ButtonGroup->setTitle("Profile List");

    Profile_ListView = new QListView( Profile_ButtonGroup, "Profile_ListView" );
    Profile_ListView->addColumn("Profile");
    Profile_ListView->addColumn("SSID");
    Profile_ListView->addColumn("Channel");
    Profile_ListView->addColumn("Authentication");
    Profile_ListView->addColumn("Encryption");
    Profile_ListView->addColumn("Network Type");
    Profile_ListView->setSelectionMode( QListView::Single );
    Profile_ListView->setAllColumnsShowFocus( TRUE ); 
    Profile_ListView->setGeometry( QRect( 8, 20, 530, 350 ) ); 

    Profile_PushButton_Add = new QPushButton( Profile_ButtonGroup, "Profile_PushButton_Add" );
    Profile_PushButton_Add->setGeometry( QRect( 8, 375, 120, 30 ) ); 
    Profile_PushButton_Add->setText("&ADD");

    Profile_PushButton_Delete = new QPushButton( Profile_ButtonGroup, "Profile_PushButton_Delete" );
    Profile_PushButton_Delete->setGeometry( QRect( 145, 375, 120, 30 ) ); 
    Profile_PushButton_Delete->setText("&DELETE");
    Profile_PushButton_Delete->setEnabled(FALSE);

    Profile_PushButton_Edit = new QPushButton( Profile_ButtonGroup, "Profile_PushButton_Edit" );
    Profile_PushButton_Edit->setGeometry( QRect( 282, 375, 120, 30 ) ); 
    Profile_PushButton_Edit->setText("&EDIT");
    Profile_PushButton_Edit->setEnabled(FALSE);

    Profile_PushButton_Activate = new QPushButton( Profile_ButtonGroup, "Profile_PushButton_Activate" );
    Profile_PushButton_Activate->setGeometry( QRect( 419, 375, 120, 30 ) ); 
    Profile_PushButton_Activate->setText("A&CTIVATE");
    Profile_PushButton_Activate->setEnabled(FALSE);

    TabWidgetRaConfig->insertTab( ProfilePage_tab,"Profile");
//===============================================================================
//LinkStatus Page
//===============================================================================
    LinkStatusPage_tab = new QWidget( TabWidgetRaConfig, "LinkStatusPage_tab" );

    LinkStatus_TextLabel1 = new QLabel( LinkStatusPage_tab, "LinkStatus_TextLabel1" );
    LinkStatus_TextLabel1->setGeometry( QRect( 50, 20, 110, 30 ) ); 
    LinkStatus_TextLabel1->setText("Status:");

    LinkStatus_TextLabel_Status = new QLabel( LinkStatusPage_tab, "LinkStatus_TextLabel_Status" );
    LinkStatus_TextLabel_Status->setGeometry( QRect( 230, 20, 300, 30 ) ); 
    LinkStatus_TextLabel_Status->setFrameShape( QLabel::LineEditPanel );
    LinkStatus_TextLabel_Status->setFrameShadow( QLabel::Sunken );

    LinkStatus_TextLabel2 = new QLabel( LinkStatusPage_tab, "LinkStatus_TextLabel2" );
    LinkStatus_TextLabel2->setGeometry( QRect( 50, 65, 120, 30 ) ); 
    LinkStatus_TextLabel2->setText("Current Channel:");

    LinkStatus_TextLabel_Channel = new QLabel( LinkStatusPage_tab, "LinkStatus_TextLabel_Channel" );
    LinkStatus_TextLabel_Channel->setGeometry( QRect( 230, 65, 300, 30 ) ); 
    LinkStatus_TextLabel_Channel->setFrameShape( QLabel::LineEditPanel );
    LinkStatus_TextLabel_Channel->setFrameShadow( QLabel::Sunken );

    LinkStatus_TextLabel3 = new QLabel( LinkStatusPage_tab, "LinkStatus_TextLabel3" );
    LinkStatus_TextLabel3->setGeometry( QRect( 50, 110, 130, 30 ) ); 
    LinkStatus_TextLabel3->setText("Current Tx Rate:");

    LinkStatus_TextLabel_TxRate = new QLabel( LinkStatusPage_tab, "LinkStatus_TextLabel_TxRate" );
    LinkStatus_TextLabel_TxRate->setGeometry( QRect( 230, 110, 300, 30 ) ); 
    LinkStatus_TextLabel_TxRate->setFrameShape( QLabel::LineEditPanel );
    LinkStatus_TextLabel_TxRate->setFrameShadow( QLabel::Sunken );
    LinkStatus_TextLabel_TxRate->setText("");

    LinkStatus_TextLabel4 = new QLabel( LinkStatusPage_tab, "LinkStatus_TextLabel4" );
    LinkStatus_TextLabel4->setGeometry( QRect( 50, 155, 150, 30 ) ); 
    LinkStatus_TextLabel4->setText("Throughput (KBits/sec):");

    LinkStatus_TextLabel5 = new QLabel( LinkStatusPage_tab, "LinkStatus_TextLabel5" );
    LinkStatus_TextLabel5->setGeometry( QRect( 230, 155, 50, 30 ) ); 
    LinkStatus_TextLabel5->setText("TX");

    LinkStatus_TextLabel_TxThrougput = new QLabel( LinkStatusPage_tab, "LinkStatus_TextLabel_TxThrougput" );
    LinkStatus_TextLabel_TxThrougput->setGeometry( QRect( 300, 155, 70, 30 ) ); 
    LinkStatus_TextLabel_TxThrougput->setFrameShape( QLabel::LineEditPanel );
    LinkStatus_TextLabel_TxThrougput->setFrameShadow( QLabel::Sunken );
    LinkStatus_TextLabel_TxThrougput->setText("");

    LinkStatus_TextLabel6 = new QLabel( LinkStatusPage_tab, "LinkStatus_TextLabel6" );
    LinkStatus_TextLabel6->setGeometry( QRect( 390, 155, 50, 30 ) ); 
    LinkStatus_TextLabel6->setText("RX");

    LinkStatus_TextLabel_RxThroughput = new QLabel( LinkStatusPage_tab, "LinkStatus_TextLabel_RxThroughput" );
    LinkStatus_TextLabel_RxThroughput->setGeometry( QRect( 460, 155, 70, 30 ) ); 
    LinkStatus_TextLabel_RxThroughput->setFrameShape( QLabel::LineEditPanel );
    LinkStatus_TextLabel_RxThroughput->setFrameShadow( QLabel::Sunken );
    LinkStatus_TextLabel_RxThroughput->setText("");

    LinkStatus_TextLabel7 = new QLabel( LinkStatusPage_tab, "LinkStatus_TextLabel7" );
    LinkStatus_TextLabel7->setGeometry( QRect( 50, 230, 120, 30 ) ); 
    LinkStatus_TextLabel7->setText("Link Quality:");

    LinkStatus_TextLabel_Link = new QLabel( LinkStatusPage_tab, "LinkStatus_TextLabel_Link" );
    LinkStatus_TextLabel_Link->setGeometry( QRect( 230, 200, 80, 20 ) ); 
    LinkStatus_TextLabel_Link->setText("");

    LinkStatus_ProgressBar_Link = new QProgressBar( LinkStatusPage_tab, "LinkStatus_ProgressBar_Link" );
    LinkStatus_ProgressBar_Link->setGeometry( QRect( 230, 230, 300, 30 ) ); 

    LinkStatus_TextLabel8 = new QLabel( LinkStatusPage_tab, "LinkStatus_TextLabel8" );
    LinkStatus_TextLabel8->setGeometry( QRect( 50, 305, 131, 31 ) ); 
    LinkStatus_TextLabel8->setText("Signal Strength:");

    LinkStatus_TextLabel_Signal = new QLabel( LinkStatusPage_tab, "LinkStatus_TextLabel_Signal" );
    LinkStatus_TextLabel_Signal->setGeometry( QRect( 230, 275, 80, 20 ) ); 
    LinkStatus_TextLabel_Signal->setText("");

    LinkStatus_CheckBox_dbm = new QCheckBox( LinkStatusPage_tab, "LinkStatus_CheckBox_dbm" );
    LinkStatus_CheckBox_dbm->setGeometry( QRect( 325, 275, 110, 20 ) ); 
    LinkStatus_CheckBox_dbm->setText("dBm format");

    LinkStatus_ProgressBar_Signal = new QProgressBar( LinkStatusPage_tab, "LinkStatus_ProgressBar_Signal" );
    LinkStatus_ProgressBar_Signal->setGeometry( QRect( 230, 305, 300, 30 ) ); 

    TabWidgetRaConfig->insertTab( LinkStatusPage_tab,"Link Status");
//===============================================================================
//Site Survey Page
//===============================================================================
    SiteSurveyPage_tab = new QWidget( TabWidgetRaConfig, "SiteSurveyPage_tab" );

    SiteSurvey_ButtonGroup = new QButtonGroup( SiteSurveyPage_tab, "SiteSurvey_ButtonGroup" );
    SiteSurvey_ButtonGroup->setGeometry( QRect( 10, 10, 550, 410 ) ); 
    SiteSurvey_ButtonGroup->setTitle("");

    SiteSurvey_ListView = new QListView( SiteSurvey_ButtonGroup, "SiteSurvey_ListView" );
    SiteSurvey_ListView->addColumn("SSID");
    SiteSurvey_ListView->addColumn("BSSID");
    SiteSurvey_ListView->addColumn("Signal");
    SiteSurvey_ListView->addColumn("Channel");
    SiteSurvey_ListView->addColumn("Encryption");
    SiteSurvey_ListView->addColumn("Authentication");
    SiteSurvey_ListView->addColumn("Network Type");
    SiteSurvey_ListView->setSelectionMode( QListView::Single );
    SiteSurvey_ListView->setAllColumnsShowFocus( TRUE ); 
    SiteSurvey_ListView->setGeometry( QRect( 8, 20, 530, 350 ) ); 

    SiteSurvey_LineEdit_Status = new QLineEdit( SiteSurvey_ButtonGroup, "SiteSurvey_LineEdit_Status" );
    SiteSurvey_LineEdit_Status->setEnabled( FALSE );
    SiteSurvey_LineEdit_Status->setGeometry( QRect( 8, 375, 220, 30 ) ); 

    SiteSurvey_PushButton_Rescan = new QPushButton( SiteSurvey_ButtonGroup, "SiteSurvey_PushButton_Rescan" );
    SiteSurvey_PushButton_Rescan->setGeometry( QRect( 232, 375, 100, 30 ) ); 
    SiteSurvey_PushButton_Rescan->setText("&RESCAN");

    SiteSurvey_PushButton_Connect = new QPushButton( SiteSurvey_ButtonGroup, "SiteSurvey_PushButton_Connect" );
    SiteSurvey_PushButton_Connect->setGeometry( QRect( 336, 375, 100, 30 ) ); 
    SiteSurvey_PushButton_Connect->setText("&CONNECT");
    SiteSurvey_PushButton_Connect->setEnabled( FALSE );

    SiteSurvey_PushButton_AddProfile = new QPushButton( SiteSurvey_ButtonGroup, "SiteSurvey_PushButton_AddProfile" );
    SiteSurvey_PushButton_AddProfile->setGeometry( QRect( 440, 375, 100, 30 ) ); 
    SiteSurvey_PushButton_AddProfile->setText("&ADD PROFILE");
    SiteSurvey_PushButton_AddProfile->setEnabled( FALSE );

    TabWidgetRaConfig->insertTab( SiteSurveyPage_tab,"Site Survey");
//===============================================================================
//Statistics Page
//===============================================================================
    StatisticsPage_tab = new QWidget( TabWidgetRaConfig, "StatisticsPage_tab" );

    Statistics_ButtonGroup_Tx = new QButtonGroup( StatisticsPage_tab, "Statistics_ButtonGroup_Tx" );
    Statistics_ButtonGroup_Tx->setGeometry( QRect( 10, 10, 549, 210 ) ); 
    Statistics_ButtonGroup_Tx->setTitle("Transmit Statistics");

    Statistics_TextLabel1 = new QLabel( Statistics_ButtonGroup_Tx, "Statistics_TextLabel1" );
    Statistics_TextLabel1->setGeometry( QRect( 10, 20, 151, 30 ) ); 
    Statistics_TextLabel1->setText("Frames Transmitted Successfully");

    Statistics_TextLabel2 = new QLabel( Statistics_ButtonGroup_Tx, "Statistics_TextLabel2" );
    Statistics_TextLabel2->setGeometry( QRect( 380, 20, 30, 30 ) ); 
    Statistics_TextLabel2->setText("=");

    Statistics_TextLabel_TxSuccess = new QLabel( Statistics_ButtonGroup_Tx, "Statistics_TextLabel_TxSuccess" );
    Statistics_TextLabel_TxSuccess->setGeometry( QRect( 420, 20, 100, 30 ) ); 
    Statistics_TextLabel_TxSuccess->setText("0");
    Statistics_TextLabel_TxSuccess->setAlignment( int( QLabel::AlignVCenter | QLabel::AlignRight ) );

    Statistics_TextLabel3 = new QLabel( Statistics_ButtonGroup_Tx, "Statistics_TextLabel3" );
    Statistics_TextLabel3->setGeometry( QRect( 10, 50, 218, 30 ) ); 
    Statistics_TextLabel3->setText("Frames Transmitted Successfully Without Retry");

    Statistics_TextLabel4 = new QLabel( Statistics_ButtonGroup_Tx, "Statistics_TextLabel4" );
    Statistics_TextLabel4->setGeometry( QRect( 380, 50, 30, 30 ) ); 
    Statistics_TextLabel4->setText("=");

    Statistics_TextLabel_TxWithoutRetry = new QLabel( Statistics_ButtonGroup_Tx, "Statistics_TextLabel_TxWithoutRetry" );
    Statistics_TextLabel_TxWithoutRetry->setGeometry( QRect( 420, 50, 100, 28 ) ); 
    Statistics_TextLabel_TxWithoutRetry->setText("0");
    Statistics_TextLabel_TxWithoutRetry->setAlignment( int( QLabel::AlignVCenter | QLabel::AlignRight ) );

    Statistics_TextLabel5 = new QLabel( Statistics_ButtonGroup_Tx, "Statistics_TextLabel5" );
    Statistics_TextLabel5->setGeometry( QRect( 10, 80, 219, 30 ) ); 
    Statistics_TextLabel5->setText("Frames Transmitted Successfully After Retry(s)");

    Statistics_TextLabel6 = new QLabel( Statistics_ButtonGroup_Tx, "Statistics_TextLabel6" );
    Statistics_TextLabel6->setGeometry( QRect( 380, 80, 30, 30 ) ); 
    Statistics_TextLabel6->setText("=");

    Statistics_TextLabel_TxAfterRetry = new QLabel( Statistics_ButtonGroup_Tx, "Statistics_TextLabel_TxAfterRetry" );
    Statistics_TextLabel_TxAfterRetry->setGeometry( QRect( 420, 80, 100, 30 ) ); 
    Statistics_TextLabel_TxAfterRetry->setText("0");
    Statistics_TextLabel_TxAfterRetry->setAlignment( int( QLabel::AlignVCenter | QLabel::AlignRight ) );

    Statistics_TextLabel7 = new QLabel( Statistics_ButtonGroup_Tx, "Statistics_TextLabel7" );
    Statistics_TextLabel7->setGeometry( QRect( 10, 110, 207, 30 ) ); 
    Statistics_TextLabel7->setText("Frames Fail To Receive ACK After All Retries");

    Statistics_TextLabel8 = new QLabel( Statistics_ButtonGroup_Tx, "Statistics_TextLabel8" );
    Statistics_TextLabel8->setGeometry( QRect( 380, 110, 30, 30 ) ); 
    Statistics_TextLabel8->setText("=");

    Statistics_TextLabel_TxFailACK = new QLabel( Statistics_ButtonGroup_Tx, "Statistics_TextLabel_TxFailACK" );
    Statistics_TextLabel_TxFailACK->setGeometry( QRect( 420, 110, 100, 30 ) ); 
    Statistics_TextLabel_TxFailACK->setText("0");
    Statistics_TextLabel_TxFailACK->setAlignment( int( QLabel::AlignVCenter | QLabel::AlignRight ) );

    Statistics_TextLabel9 = new QLabel( Statistics_ButtonGroup_Tx, "Statistics_TextLabel9" );
    Statistics_TextLabel9->setGeometry( QRect( 10, 140, 172, 30 ) ); 
    Statistics_TextLabel9->setText("RTS Frames Sucessfully Receive CTS");

    Statistics_TextLabel10 = new QLabel( Statistics_ButtonGroup_Tx, "Statistics_TextLabel10" );
    Statistics_TextLabel10->setGeometry( QRect( 380, 140, 30, 30 ) ); 
    Statistics_TextLabel10->setText("=");

    Statistics_TextLabel_RTSSuccess = new QLabel( Statistics_ButtonGroup_Tx, "Statistics_TextLabel_RTSSuccess" );
    Statistics_TextLabel_RTSSuccess->setGeometry( QRect( 420, 140, 100, 30 ) ); 
    Statistics_TextLabel_RTSSuccess->setText("0");
    Statistics_TextLabel_RTSSuccess->setAlignment( int( QLabel::AlignVCenter | QLabel::AlignRight ) );

    Statistics_TextLabel11 = new QLabel( Statistics_ButtonGroup_Tx, "Statistics_TextLabel11" );
    Statistics_TextLabel11->setGeometry( QRect( 10, 170, 151, 30 ) ); 
    Statistics_TextLabel11->setText("RTS Frames Fail To Receive CTS");

    Statistics_TextLabel12 = new QLabel( Statistics_ButtonGroup_Tx, "Statistics_TextLabel12" );
    Statistics_TextLabel12->setGeometry( QRect( 380, 170, 30, 30 ) ); 
    Statistics_TextLabel12->setText("=");

    Statistics_TextLabel_RTSFail = new QLabel( Statistics_ButtonGroup_Tx, "Statistics_TextLabel_RTSFail" );
    Statistics_TextLabel_RTSFail->setGeometry( QRect( 420, 170, 100, 30 ) ); 
    Statistics_TextLabel_RTSFail->setText("0");
    Statistics_TextLabel_RTSFail->setAlignment( int( QLabel::AlignVCenter | QLabel::AlignRight ) );

    Statistics_ButtonGroup_Rx = new QButtonGroup( StatisticsPage_tab, "Statistics_ButtonGroup_Rx" );
    Statistics_ButtonGroup_Rx->setGeometry( QRect( 10, 228, 549, 150 ) ); 
    Statistics_ButtonGroup_Rx->setTitle("Receive Statistics");

    Statistics_TextLabel13 = new QLabel( Statistics_ButtonGroup_Rx, "Statistics_TextLabel13" );
    Statistics_TextLabel13->setGeometry( QRect( 10, 20, 138, 30 ) ); 
    Statistics_TextLabel13->setText("Frames Received Successfully");

    Statistics_TextLabel14 = new QLabel( Statistics_ButtonGroup_Rx, "Statistics_TextLabel14" );
    Statistics_TextLabel14->setGeometry( QRect( 380, 20, 30, 30 ) ); 
    Statistics_TextLabel14->setText("=");

    Statistics_TextLabel_RxSuccess = new QLabel( Statistics_ButtonGroup_Rx, "Statistics_TextLabel_RxSuccess" );
    Statistics_TextLabel_RxSuccess->setGeometry( QRect( 420, 20, 100, 30 ) ); 
    Statistics_TextLabel_RxSuccess->setText("0");
    Statistics_TextLabel_RxSuccess->setAlignment( int( QLabel::AlignVCenter | QLabel::AlignRight ) );

    Statistics_TextLabel15 = new QLabel( Statistics_ButtonGroup_Rx, "Statistics_TextLabel15" );
    Statistics_TextLabel15->setGeometry( QRect( 10, 50, 158, 30 ) ); 
    Statistics_TextLabel15->setText("Frames Received With CRC Error");

    Statistics_TextLabel16 = new QLabel( Statistics_ButtonGroup_Rx, "Statistics_TextLabel16" );
    Statistics_TextLabel16->setGeometry( QRect( 380, 50, 30, 30 ) ); 
    Statistics_TextLabel16->setText("=");

    Statistics_TextLabel_RxCRC = new QLabel( Statistics_ButtonGroup_Rx, "Statistics_TextLabel_RxCRC" );
    Statistics_TextLabel_RxCRC->setGeometry( QRect( 420, 50, 100, 30 ) ); 
    Statistics_TextLabel_RxCRC->setText("0");
    Statistics_TextLabel_RxCRC->setAlignment( int( QLabel::AlignVCenter | QLabel::AlignRight ) );

    Statistics_TextLabel17 = new QLabel( Statistics_ButtonGroup_Rx, "Statistics_TextLabel17" );
    Statistics_TextLabel17->setGeometry( QRect( 10, 80, 195, 30 ) ); 
    Statistics_TextLabel17->setText("Frames Dropped Due To Out-of-Resource");

    Statistics_TextLabel18 = new QLabel( Statistics_ButtonGroup_Rx, "Statistics_TextLabel18" );
    Statistics_TextLabel18->setGeometry( QRect( 380, 80, 30, 30 ) ); 
    Statistics_TextLabel18->setText("=");

    Statistics_TextLabel_RxDrop = new QLabel( Statistics_ButtonGroup_Rx, "Statistics_TextLabel_RxDrop" );
    Statistics_TextLabel_RxDrop->setGeometry( QRect( 420, 80, 100, 30 ) ); 
    Statistics_TextLabel_RxDrop->setText("0");
    Statistics_TextLabel_RxDrop->setAlignment( int( QLabel::AlignVCenter | QLabel::AlignRight ) );

    Statistics_TextLabel19 = new QLabel( Statistics_ButtonGroup_Rx, "Statistics_TextLabel19" );
    Statistics_TextLabel19->setGeometry( QRect( 10, 110, 125, 30 ) ); 
    Statistics_TextLabel19->setText("Duplicate Frames Received");

    Statistics_TextLabel20 = new QLabel( Statistics_ButtonGroup_Rx, "Statistics_TextLabel20" );
    Statistics_TextLabel20->setGeometry( QRect( 380, 110, 30, 30 ) ); 
    Statistics_TextLabel20->setText("=");

    Statistics_TextLabel_Duplicate = new QLabel( Statistics_ButtonGroup_Rx, "Statistics_TextLabel_Duplicate" );
    Statistics_TextLabel_Duplicate->setGeometry( QRect( 420, 110, 100, 30 ) ); 
    Statistics_TextLabel_Duplicate->setText("0");
    Statistics_TextLabel_Duplicate->setAlignment( int( QLabel::AlignVCenter | QLabel::AlignRight ) );

    Statistics_PushButton_Reset = new QPushButton( StatisticsPage_tab, "Statistics_PushButton_Reset" );
    Statistics_PushButton_Reset->setGeometry( QRect( 428, 388, 130, 30 ) ); 
    Statistics_PushButton_Reset->setText("&RESET COUNTERS");

    TabWidgetRaConfig->insertTab( StatisticsPage_tab, "Statistics");
//===============================================================================
//Advance Page
//===============================================================================
    AdvancePage_tab = new QWidget( TabWidgetRaConfig, "AdvancePage_tab" );

    Advance_TextLabel1 = new QLabel( AdvancePage_tab, "Advance_TextLabel1" );
    Advance_TextLabel1->setGeometry( QRect( 30, 20, 110, 30 ) ); 
    Advance_TextLabel1->setText("Wireless Mode");

    Advance_ComboBox_Mode = new QComboBox( FALSE, AdvancePage_tab, "Advance_ComboBox_Mode" );
    Advance_ComboBox_Mode->insertItem("802.11 B/G mixed mode");
    Advance_ComboBox_Mode->insertItem("802.11 B only");
    Advance_ComboBox_Mode->setGeometry( QRect( 160, 18, 201, 31 ) ); 

    Advance_CheckBox_TxBurst = new QCheckBox( AdvancePage_tab, "Advance_CheckBox_TxBurst" );
    Advance_CheckBox_TxBurst->setGeometry( QRect( 30, 70, 200, 30 ) ); 
    Advance_CheckBox_TxBurst->setText("Enable TX Burst");

    Advance_CheckBox_AdhocOfdm = new QCheckBox( AdvancePage_tab, "Advance_CheckBox_AdhocOfdm" );
    Advance_CheckBox_AdhocOfdm->setGeometry( QRect( 30, 110, 200, 30 ) ); 
    Advance_CheckBox_AdhocOfdm->setText("Ad Hoc mode use OFDM rate");

    Advance_CheckBox_ShortSlot = new QCheckBox( AdvancePage_tab, "Advance_CheckBox_ShortSlot" );
    Advance_CheckBox_ShortSlot->setEnabled( FALSE );
    Advance_CheckBox_ShortSlot->setGeometry( QRect( 30, 150, 200, 30 ) ); 
    Advance_CheckBox_ShortSlot->setText("Use Short Slot Time when applicable");

    Advance_CheckBox_TurboRate = new QCheckBox( AdvancePage_tab, "Advance_CheckBox_TurboRate" );
    Advance_CheckBox_TurboRate->setEnabled( FALSE );
    Advance_CheckBox_TurboRate->setGeometry( QRect( 30, 190, 200, 30 ) ); 
    Advance_CheckBox_TurboRate->setText("Use Turbo rate (72/100Mbps) when applicable");

    Advance_TextLabel2 = new QLabel( AdvancePage_tab, "Advance_TextLabel2" );
    Advance_TextLabel2->setGeometry( QRect( 300, 70, 120, 30 ) ); 
    Advance_TextLabel2->setText("11B/G Protection");

    Advance_ComboBox_BGProtection = new QComboBox( FALSE, AdvancePage_tab, "Advance_ComboBox_BGProtection" );
    Advance_ComboBox_BGProtection->insertItem("Auto");
    Advance_ComboBox_BGProtection->insertItem("On");
    Advance_ComboBox_BGProtection->insertItem("Off");
    Advance_ComboBox_BGProtection->setEnabled( TRUE );
    Advance_ComboBox_BGProtection->setGeometry( QRect( 430, 70, 120, 30 ) ); 

    Advance_TextLabel3 = new QLabel( AdvancePage_tab, "Advance_TextLabel3" );
    Advance_TextLabel3->setGeometry( QRect( 300, 110, 120, 30 ) ); 
    Advance_TextLabel3->setText("TX Rate");

    Advance_ComboBox_TxRate = new QComboBox( FALSE, AdvancePage_tab, "Advance_ComboBox_TxRate" );
    Advance_ComboBox_TxRate->insertItem("Auto");
    Advance_ComboBox_TxRate->insertItem("1 Mbps");
    Advance_ComboBox_TxRate->insertItem("2 Mbps");
    Advance_ComboBox_TxRate->insertItem("5.5 Mbps");
    Advance_ComboBox_TxRate->insertItem("11 Mbps");
    Advance_ComboBox_TxRate->insertItem("6 Mbps");
    Advance_ComboBox_TxRate->insertItem("9 Mbps");
    Advance_ComboBox_TxRate->insertItem("12 Mbps");
    Advance_ComboBox_TxRate->insertItem("18 Mbps");
    Advance_ComboBox_TxRate->insertItem("24 Mbps");
    Advance_ComboBox_TxRate->insertItem("36 Mbps");
    Advance_ComboBox_TxRate->insertItem("48 Mbps");
    Advance_ComboBox_TxRate->insertItem("54 Mbps");
    Advance_ComboBox_TxRate->setGeometry( QRect( 430, 110, 120, 30 ) ); 

    Advance_TextLabel_Radio = new QLabel( AdvancePage_tab, "Advance_TextLabel_Radio" );
    Advance_TextLabel_Radio->setGeometry( QRect( 45, 380, 30, 30 ) ); 
    Advance_TextLabel_Radio->setText("");
    Advance_TextLabel_Radio->setPixmap( uic_load_pixmap_RaConfigForm( "radioon.png" ) );

    Advance_PushButton_Radio = new QPushButton( AdvancePage_tab, "Advance_PushButton_Radio" );
    Advance_PushButton_Radio->setGeometry( QRect( 80, 380, 120, 30 ) ); 
    Advance_PushButton_Radio->setText("&RADIO OFF");

    Advance_PushButton_Apply = new QPushButton( AdvancePage_tab, "Advance_PushButton_Apply" );
    Advance_PushButton_Apply->setGeometry( QRect( 420, 380, 120, 30 ) ); 
    Advance_PushButton_Apply->setText("&APPLY");

    TabWidgetRaConfig->insertTab( AdvancePage_tab, "Advance");
//===============================================================================
//About Page
//===============================================================================
    AboutPage_tab = new QWidget( TabWidgetRaConfig, "AboutPage_tab" );

    About_TextLabel_Logo = new QLabel( AboutPage_tab, "About_TextLabel_Logo" );
    About_TextLabel_Logo->setGeometry( QRect( 30, 30, 161, 91 ) ); 
    About_TextLabel_Logo->setText("");
    About_TextLabel_Logo->setPixmap( uic_load_pixmap_RaConfigForm( "rtlogo.png" ) );

    About_ButtonGroupUI = new QButtonGroup( AboutPage_tab, "About_ButtonGroupUI" );
    About_ButtonGroupUI->setGeometry( QRect( 30, 140, 510, 60 ) ); 
    About_ButtonGroupUI->setTitle("Configuration Utility - Rt2500");

    About_TextLabel1 = new QLabel( About_ButtonGroupUI, "About_TextLabel1" );
    About_TextLabel1->setGeometry( QRect( 20, 20, 80, 30 ) ); 
    About_TextLabel1->setText("Version:");

    About_TextLabel_UIVersion = new QLabel( About_ButtonGroupUI, "About_TextLabel_UIVersion" );
    About_TextLabel_UIVersion->setGeometry( QRect( 110, 20, 100, 30 ) ); 
    About_TextLabel_UIVersion->setText(CONFIGURATION_UI_VERSION);

    About_TextLabel2 = new QLabel( About_ButtonGroupUI, "About_TextLabel2" );
    About_TextLabel2->setGeometry( QRect( 280, 20, 80, 30 ) ); 
    About_TextLabel2->setText("Date:");

    About_TextLabel_UIDate = new QLabel( About_ButtonGroupUI, "About_TextLabel_UIDate" );
    About_TextLabel_UIDate->setGeometry( QRect( 370, 20, 100, 30 ) ); 
    About_TextLabel_UIDate->setText(CONFIGURATION_UI_DATE);

    About_ButtonGroupNIC = new QButtonGroup( AboutPage_tab, "About_ButtonGroupNIC" );
    About_ButtonGroupNIC->setGeometry( QRect( 30, 230, 510, 60 ) ); 
    About_ButtonGroupNIC->setTitle("NIC Driver");

    About_TextLabel3 = new QLabel( About_ButtonGroupNIC, "About_TextLabel3" );
    About_TextLabel3->setGeometry( QRect( 20, 20, 80, 30 ) ); 
    About_TextLabel3->setText("Version:");

    About_TextLabel_NICVersion = new QLabel( About_ButtonGroupNIC, "About_TextLabel_NICVersion" );
    About_TextLabel_NICVersion->setGeometry( QRect( 110, 20, 100, 30 ) ); 

    About_TextLabel4 = new QLabel( About_ButtonGroupNIC, "About_TextLabel4" );
    About_TextLabel4->setGeometry( QRect( 280, 20, 80, 30 ) ); 
    About_TextLabel4->setText("Date:");

    About_TextLabel_NICDate = new QLabel( About_ButtonGroupNIC, "About_TextLabel_NICDate" );
    About_TextLabel_NICDate->setGeometry( QRect( 370, 20, 100, 30 ) ); 

    About_ButtonGroupMAC = new QButtonGroup( AboutPage_tab, "About_ButtonGroupMAC" );
    About_ButtonGroupMAC->setGeometry( QRect( 30, 320, 510, 60 ) ); 
    About_ButtonGroupMAC->setTitle("Mac Address");

    About_TextLabel5 = new QLabel( About_ButtonGroupMAC, "About_TextLabel5" );
    About_TextLabel5->setGeometry( QRect( 20, 20, 130, 30 ) ); 
    About_TextLabel5->setText("Phy_Address:");

    About_TextLabel_PhyAddress = new QLabel( About_ButtonGroupMAC, "About_TextLabel_PhyAddress" );
    About_TextLabel_PhyAddress->setGeometry( QRect( 170, 20, 170, 30 ) ); 
    About_TextLabel_PhyAddress->setText("");

    TabWidgetRaConfig->insertTab( AboutPage_tab,"About");

    TabWidgetRaConfig->showPage(SiteSurveyPage_tab);  //Site survey.

    connect( TabWidgetRaConfig, SIGNAL( currentChanged(QWidget*) ), this, SLOT( OnPageChanged() ) );
    connect( Profile_PushButton_Add, SIGNAL( clicked() ), this, SLOT( Profile_OnAddProfile() ) );
    connect( Profile_PushButton_Delete, SIGNAL( clicked() ), this, SLOT( Profile_OnDeleteProfile() ) );
    connect( Profile_PushButton_Edit, SIGNAL( clicked() ), this, SLOT( Profile_OnEditProfile() ) );
    connect( Profile_PushButton_Activate, SIGNAL( clicked() ), this, SLOT( Profile_OnActiveProfile() ) );
    connect( Profile_ListView, SIGNAL( doubleClicked(QListViewItem*) ), this, SLOT( Profile_OnEditProfile() ) );
    connect( SiteSurvey_PushButton_Rescan, SIGNAL( clicked() ), this, SLOT( SiteSurvey_OnRescan() ) );
    connect( SiteSurvey_PushButton_Connect, SIGNAL( clicked() ), this, SLOT( SiteSurvey_OnConnect() ) );
    connect( SiteSurvey_PushButton_AddProfile, SIGNAL( clicked() ), this, SLOT( SiteSurvey_OnAddToProfile() ) );
    connect( SiteSurvey_ListView, SIGNAL( doubleClicked(QListViewItem*) ), this, SLOT( SiteSurvey_OnConnect() ) );
    connect( SiteSurvey_ListView, SIGNAL( selectionChanged(QListViewItem*) ), this, SLOT( SiteSurvey_OnSelectChange() ) );
    connect( Statistics_PushButton_Reset, SIGNAL( clicked() ), this, SLOT( Statistics_OnResetCounters() ) );
    connect( Advance_PushButton_Radio, SIGNAL( clicked() ), this, SLOT( Advance_OnRadio() ) );
    connect( Advance_PushButton_Apply, SIGNAL( clicked() ), this, SLOT( Advance_OnApply() ) );
    connect( Advance_PushButton_Apply, SIGNAL( clicked() ), this, SLOT( Advance_OnApply() ) );
    connect( Advance_ComboBox_Mode, SIGNAL( activated(int) ), this, SLOT( Advance_OnSelchangeWirelessMode(int) ) );


    m_nSocketId = socket_id;
    m_strDeviceName = (char *)malloc(strlen(device_name)+1);
    if(m_strDeviceName)
        strcpy(m_strDeviceName, device_name);

    timerId_Alive = startTimer(2000); //check device driver per 2 seconds.
    timerId_ConnectStatus = -1;
    timerId_LinkStatus = -1;
    timerId_Statistic = -1;
    timerId_UpdateProfileStatus = -1;

    m_pBssidList = (PNDIS_802_11_BSSID_LIST_EX) malloc(65536);  //64k
    m_pProfileSetting = NULL;
    m_bSetSsid = FALSE;
    m_bSetBssid = FALSE;
    m_bRescan = FALSE;
    m_nTimerCount = 0;
    m_lTxCount = 0;
    m_lRxCount = 0;
    m_lChannelQuality = 0;
    m_WirelessMode = PHY_11BG_MIXED;
    m_bTXBurst = FALSE;
    m_nBGProtection = 0;
    m_bShortSlot = FALSE;
    m_bTurboRate = FALSE;
    m_bAdhocOfdm = FALSE;
    m_nTXRate = 0;
    m_nSigQua=0;
    m_bUpdateSiteSurveyPage = TRUE;
    m_bUpdateProfilePage    = TRUE;
    m_bUpdateLinkSatusPage = TRUE;

    memset(&m_BssidSet, 0x00, sizeof(m_BssidSet));
    memset(&m_SsidSet, 0x00, sizeof(m_SsidSet));

    Profile_ReadProfileFromFile();

    if (!G_bUserAdmin)
    {
        Profile_PushButton_Add->setEnabled(FALSE);
        Profile_PushButton_Delete->setEnabled(FALSE);
        Profile_PushButton_Edit->setEnabled(FALSE);
        Profile_PushButton_Activate->setEnabled(FALSE);

        Advance_ComboBox_Mode->setEnabled( FALSE );
        Advance_CheckBox_TxBurst->setEnabled( FALSE );
        Advance_CheckBox_ShortSlot->setEnabled( FALSE );
        Advance_CheckBox_TurboRate->setEnabled( FALSE );
        Advance_ComboBox_BGProtection->setEnabled( FALSE );
        Advance_ComboBox_TxRate->setEnabled( FALSE );
        Advance_PushButton_Radio->setEnabled( FALSE );
        Advance_PushButton_Apply->setEnabled( FALSE );
    }

    ULONG RadioStatus;

    OidQueryInformation(RT_OID_802_11_RADIO, m_nSocketId, m_strDeviceName, &RadioStatus, sizeof(RadioStatus));
    if (RadioStatus)
        G_bRadio = TRUE;
    else
        G_bRadio = FALSE;
}

/*  
 *  Destroys the object and frees any allocated resources
 */
RaConfigForm::~RaConfigForm()
{
    // no need to delete child widgets, Qt does it all for us
}

void RaConfigForm::OnPageChanged()
{
    killTimer(timerId_LinkStatus);
    timerId_LinkStatus = -1;
    killTimer(timerId_ConnectStatus);
    timerId_ConnectStatus = -1;
    killTimer(timerId_Statistic);
    timerId_Statistic = -1;
    killTimer(timerId_UpdateProfileStatus);
    timerId_UpdateProfileStatus = -1;

    switch(TabWidgetRaConfig->currentPageIndex())
    {
        case 0: //Profile Page
            Profile_OnActive();
            break;
        case 1: //Link Status page
            LinkStatus_OnActive();
            break;
        case 2: //Site Survey page
            SiteSurvey_OnActive();
            break;
        case 3: //Statistics page
            Statistics_OnActive();
            break;
        case 4: //Advance page
            Advance_OnActive();
            break;
        case 5: //About page
            About_OnActive();
            break;
    }

}

void RaConfigForm::timerEvent(QTimerEvent* e)
{
    NDIS_802_11_MAC_ADDRESS        CurrentAddress;

    if (e->timerId() == timerId_Alive)
    {
        if(OidQueryInformation(OID_802_3_CURRENT_ADDRESS, m_nSocketId, m_strDeviceName, &CurrentAddress, sizeof(CurrentAddress)) == -1 &&
            errno == ENODEV) //No such device from errno.h
        {
            killTimers();
            close();
        }
    }
    else if (e->timerId() == timerId_ConnectStatus)
    {
        SiteSurvey_ProbeConnectStatus();
        SiteSurvey_ButtonShowHide();
    }
    else if (e->timerId() == timerId_LinkStatus)
        LinkStatus_UpdateStatus();
    else if (e->timerId() == timerId_Statistic)
        Statistics_OnTimer();
    else if (e->timerId() == timerId_UpdateProfileStatus)
        Profile_UpdateProfileStatus();
}

void RaConfigForm::Profile_ReadProfileFromFile()
{
    QListViewItem               *Item;
    PRT_PROFILE_SETTING         nowProfileSetting=NULL;
    PRT_PROFILE_SETTING         lastProfileSetting=NULL;
    RT_PROFILE_SETTING          tmpProfileSetting;
    NDIS_802_11_SSID            SsidQuery;
    NDIS_MEDIA_STATE            ConnectStatus;
    FILE                        *cfgProfileId;
    char                        strSSID[NDIS_802_11_LENGTH_SSID + 1];
    char                        cfgProfile[512];
    char                        tempstr[255];

    memset(m_strActiveProfileID, 0x00,  32+1);
    getkeystring("Default", "ProfileID", m_strActiveProfileID, 32, RT2500_SYSTEM_PATH, RT2500_SYSTEM_DATA);

    sprintf(cfgProfile, "%s/%s", RT2500_SYSTEM_PATH, RT2500_UI_PROFILE);
    lastProfileSetting = NULL;
    if ((cfgProfileId = fopen(cfgProfile, "rb")) != NULL)
    {
        while (fread((void *)&tmpProfileSetting, sizeof(RT_PROFILE_SETTING), (unsigned) 1, cfgProfileId) != 0)
        {
            if (tmpProfileSetting.ProfileDataType != RT2500_UI_TYPE)
                break;   //not for RT2500 Utility

            if (( nowProfileSetting = (PRT_PROFILE_SETTING) malloc(sizeof(RT_PROFILE_SETTING))) == NULL)
                break;

            memcpy(nowProfileSetting, (void *)&tmpProfileSetting, sizeof(RT_PROFILE_SETTING));
            nowProfileSetting->Next=lastProfileSetting;
            lastProfileSetting = nowProfileSetting;

            Item = new QListViewItem(Profile_ListView);
            if (strcmp(m_strActiveProfileID, (const char *)nowProfileSetting->Profile) == 0)
            {
                if (OidQueryInformation(OID_GEN_MEDIA_CONNECT_STATUS, m_nSocketId, m_strDeviceName, &ConnectStatus, sizeof(ConnectStatus)) >= 0)
                {
                    if(ConnectStatus == NdisMediaStateConnected && G_bRadio)
                    {
                        memset(&SsidQuery, 0x00, sizeof(SsidQuery));
                        OidQueryInformation(OID_802_11_SSID, m_nSocketId, m_strDeviceName, &SsidQuery, sizeof(SsidQuery));

                        memset(strSSID, 0x00, NDIS_802_11_LENGTH_SSID + 1);
                        memcpy(strSSID, SsidQuery.Ssid, SsidQuery.SsidLength);

                        if (strcmp(strSSID, (const char *)nowProfileSetting->SSID) == 0)
                            Item->setPixmap(0, uic_load_pixmap_RaConfigForm("check16.xpm"));
                        else
                            Item->setPixmap(0, uic_load_pixmap_RaConfigForm("noactive16.xpm"));
                    }
                    else
                        Item->setPixmap(0, uic_load_pixmap_RaConfigForm("noactive16.xpm"));
                }
                else
                    Item->setPixmap(0, uic_load_pixmap_RaConfigForm("noactive16.xpm"));
            }
            else
            {
                Item->setPixmap(0, uic_load_pixmap_RaConfigForm("uncheck16.xpm"));
            }

            Item->setText(0, (const char *)nowProfileSetting->Profile);
            Item->setText(1, (const char *)nowProfileSetting->SSID);

            if(nowProfileSetting->Channel != 0)
            {
                sprintf(tempstr, "%d", nowProfileSetting->Channel);
                Item->setText(2, tempstr);
            }
            else
                Item->setText(2, "Auto");

            if (nowProfileSetting->Authentication == Ndis802_11AuthModeOpen)
                Item->setText(3, "OPEN");
            else if (nowProfileSetting->Authentication == Ndis802_11AuthModeShared)
                Item->setText(3, "SHARED");
            else if (nowProfileSetting->Authentication == Ndis802_11AuthModeWPAPSK)
                Item->setText(3, "WPAPSK");
            else if (nowProfileSetting->Authentication == Ndis802_11AuthModeWPANone)
                Item->setText(3, "WPA-None");
            else if (nowProfileSetting->Authentication == Ndis802_11AuthModeWPA)
                Item->setText(3, "WPA");
            else 
                Item->setText(3, "unknown");

            if (nowProfileSetting->Encryption == Ndis802_11WEPEnabled)
                Item->setText(4,"WEP");
            else if (nowProfileSetting->Encryption == Ndis802_11WEPDisabled)
                Item->setText(4,"NONE");
            else if (nowProfileSetting->Encryption == Ndis802_11Encryption2Enabled)
                Item->setText(4,"TKIP");
            else if (nowProfileSetting->Encryption == Ndis802_11Encryption3Enabled)
                Item->setText(4,"AES");
            else
                Item->setText(4,"unknown");

            Item->setText(5, strAryNetworkType[nowProfileSetting->NetworkType]);
        }
        fclose(cfgProfileId);
        m_pProfileSetting = lastProfileSetting;
    }

    if (G_bUserAdmin)
    {
        if (Profile_ListView->childCount() > 0)
        {
            Profile_PushButton_Delete->setEnabled(TRUE);
            Profile_PushButton_Edit->setEnabled(TRUE);
            Profile_PushButton_Activate->setEnabled(TRUE);
        }
    }
}

void RaConfigForm::Profile_UpdateProfileStatus()
{
    QListViewItem                       *ListItem = NULL;
    NDIS_MEDIA_STATE                    ConnectStatus = NdisMediaStateDisconnected;
    NDIS_802_11_SSID                    SsidQuery;
    NDIS_802_11_WEP_STATUS              ProEncryp = Ndis802_11WEPDisabled, Encryp = Ndis802_11WEPDisabled;
    NDIS_802_11_AUTHENTICATION_MODE     ProAuthenType = Ndis802_11AuthModeOpen, AuthenType = Ndis802_11AuthModeOpen;
    NDIS_802_11_NETWORK_INFRASTRUCTURE  ProNetType = Ndis802_11Infrastructure, NetType = Ndis802_11Infrastructure;
    QString                             qstr;
    char                                strSSID[NDIS_802_11_LENGTH_SSID + 1];
    int                                 nItem;
    int                                 i;

    if (OidQueryInformation(OID_GEN_MEDIA_CONNECT_STATUS, m_nSocketId, m_strDeviceName, &ConnectStatus, sizeof(ConnectStatus)) < 0)
        ConnectStatus = NdisMediaStateDisconnected;

    memset(&SsidQuery, 0x00, sizeof(SsidQuery));
    memset(strSSID, 0x00, NDIS_802_11_LENGTH_SSID + 1);

    if (ConnectStatus == NdisMediaStateConnected)
    {
        if (OidQueryInformation(OID_802_11_SSID, m_nSocketId, m_strDeviceName, &SsidQuery, sizeof(SsidQuery)) >=0 )
        {
            memcpy(strSSID, SsidQuery.Ssid, SsidQuery.SsidLength);
        }
    }

    OidQueryInformation(OID_802_11_WEP_STATUS, m_nSocketId, m_strDeviceName, &Encryp, sizeof(Encryp));
    OidQueryInformation(OID_802_11_AUTHENTICATION_MODE, m_nSocketId, m_strDeviceName, &AuthenType, sizeof(AuthenType));
    OidQueryInformation(OID_802_11_INFRASTRUCTURE_MODE, m_nSocketId, m_strDeviceName, &NetType, sizeof(NetType));

    nItem = Profile_ListView->childCount();
    ListItem = Profile_ListView->firstChild();
    for (i = 0; i < nItem; i++)
    {
        qstr = ListItem->text(0);
        if (qstr.compare(m_strActiveProfileID) == 0)
        {
            qstr = ListItem->text(5);
            if (qstr.compare("Infrastructure") == 0)
                ProNetType = Ndis802_11Infrastructure;
            else
                ProNetType = Ndis802_11IBSS;

            qstr = ListItem->text(3);
            if (qstr.compare("OPEN") == 0)
                ProAuthenType = Ndis802_11AuthModeOpen;
            else if (qstr.compare("SHARED") == 0)
                ProAuthenType = Ndis802_11AuthModeShared;
            else if (qstr.compare("WPAPSK") == 0)
                ProAuthenType = Ndis802_11AuthModeWPAPSK;
            else if (qstr.compare("WPA-None") == 0)
                ProAuthenType = Ndis802_11AuthModeWPANone;
            else if (qstr.compare("WPA") == 0)
                ProAuthenType = Ndis802_11AuthModeWPA;

            qstr = ListItem->text(4);
            if (qstr.compare("WEP") == 0)
                ProEncryp = Ndis802_11WEPEnabled;
            else if (qstr.compare("NONE") == 0)
                ProEncryp = Ndis802_11WEPDisabled;
            else if (qstr.compare("TKIP") == 0)
                ProEncryp = Ndis802_11Encryption2Enabled;
            else if (qstr.compare("AES") == 0)
                ProEncryp = Ndis802_11Encryption3Enabled;

            qstr = ListItem->text(1);
            if ( ((qstr.isEmpty()) || (qstr.compare(strSSID) == 0)) && (ConnectStatus == NdisMediaStateConnected) &&
                (ProNetType == NetType) && (ProAuthenType == AuthenType) && (ProEncryp == Encryp))
                ListItem->setPixmap(0, uic_load_pixmap_RaConfigForm("check16.xpm"));
            else
                ListItem->setPixmap(0, uic_load_pixmap_RaConfigForm("noactive16.xpm"));
        }
        else
            ListItem->setPixmap(0, uic_load_pixmap_RaConfigForm("uncheck16.xpm"));

        ListItem = ListItem->itemBelow();
    }

    if (m_bUpdateSiteSurveyPage)
    {
        m_bUpdateSiteSurveyPage = FALSE;
        SiteSurvey_ProbeConnectStatus();
    }

    if (m_bUpdateLinkSatusPage)
    {
        m_bUpdateLinkSatusPage = FALSE;
        LinkStatus_UpdateStatus();
    }

}

void RaConfigForm::Profile_WriteProfileToFile()
{
    FILE                        *WriteProfileId;
    PRT_PROFILE_SETTING         ptr=NULL;
    char                        cfgProfile[512];
    char                        cmdString[256];

    if (getuid() == 0)
    {
        sprintf(cfgProfile, "%s/%s", RT2500_SYSTEM_PATH, RT2500_UI_PROFILE);
        sprintf(cmdString, " if [ ! -d %s ] ; then mkdir -p %s ; fi ", RT2500_SYSTEM_PATH, RT2500_SYSTEM_PATH);
        system(cmdString);

        if (m_pProfileSetting != NULL)
        {
            if ((WriteProfileId = fopen(cfgProfile, "wb")) != NULL)
            {
                ptr = m_pProfileSetting;
                while (ptr != NULL)
                {
                    ptr->ProfileDataType = RT2500_UI_TYPE;
                    fwrite(ptr, sizeof(RT_PROFILE_SETTING), 1, WriteProfileId);
                    ptr = ptr->Next;
                }
                fclose(WriteProfileId);
            }
        }
        else
        {
            sprintf(cmdString, "rm -f %s", cfgProfile);
            system(cmdString);
        }
    }
}

void RaConfigForm::Profile_WriteConfigToRegistryAndSetOid()
{
    QListViewItem                           *Item;
    QString                                 qstr;
    PRT_PROFILE_SETTING                     ptr=NULL;
    RT_802_11_PHY_MODE                      enumWirelessMode;
    RT_802_11_STA_CONFIG                    configStation;
    RT_802_11_STA_CONFIG                    configOldStation;
    NDIS_802_11_NETWORK_INFRASTRUCTURE      enumNetworkType;
    RT_802_11_PREAMBLE                      enumPreamType;
    NDIS_802_11_RTS_THRESHOLD               lRtsThre;
    NDIS_802_11_FRAGMENTATION_THRESHOLD     lFragThre;
    NDIS_802_11_AUTHENTICATION_MODE         enumAuthenType;
    NDIS_802_11_WEP_STATUS                  enumEncryp;
    NDIS_802_11_CONFIGURATION               Configuration;
    NDIS_802_11_POWER_MODE                  enumPSMode;
    NDIS_802_11_SSID                        SSID;
    NDIS_802_11_REMOVE_KEY                  removeKey;
    PNDIS_802_11_KEY                        pKey = NULL;
    NDIS_802_11_RATES                       aryRates;
    ULONG                                   nKeyLen;
    ULONG                                   lBufLen;
    ULONG                                   lFreq = 0;
    UCHAR                                   keyMaterial[40];
    char                                    strSSID[NDIS_802_11_LENGTH_SSID + 1];
    char                                    strtmp[255];
    int                                     i;
    bool                                    bSetSSID = FALSE;
    bool                                    bIsFound = FALSE;

    Item = Profile_ListView->currentItem();
    qstr = Item->text(0);
    ptr = m_pProfileSetting;
    while (ptr)
    {
        if (qstr.compare((const char *)ptr->Profile) == 0)
        {
            bIsFound = TRUE;
            break;
        }
            ptr = ptr->Next;
    }

    if (bIsFound)
    {
        writekeystring("Default", "ProfileID", (char *)ptr->Profile, RT2500_SYSTEM_PATH, RT2500_SYSTEM_DATA);
        strcpy(m_strActiveProfileID, (const char *)ptr->Profile);

        //Write to Registry
        //SSID
        writekeystring("Default", "SSID", (char *)ptr->SSID, RT2500_SYSTEM_PATH, RT2500_SYSTEM_DATA);

        if(!G_bSupportAMode && G_enumWirelessMode >= PHY_11A)
            G_enumWirelessMode = PHY_11BG_MIXED;

        // SetOidInformation
        OidQueryInformation(RT_OID_802_11_PHY_MODE, m_nSocketId, m_strDeviceName, &enumWirelessMode, sizeof(enumWirelessMode));
        if(enumWirelessMode != G_enumWirelessMode)
            OidSetInformation(RT_OID_802_11_PHY_MODE, m_nSocketId, m_strDeviceName, &G_enumWirelessMode, sizeof(G_enumWirelessMode));

        //Get AdhocOfdm mode
        if (getkeystring("Default", "AdhocOfdm",  strtmp, 255, RT2500_SYSTEM_PATH, RT2500_SYSTEM_DATA) == TRUE)
        {
            if (atoi(strtmp) != 0)
                m_bAdhocOfdm = TRUE;
            else
                m_bAdhocOfdm = FALSE;
        }
        else
            m_bAdhocOfdm = FALSE;

        // Get TXBurst value
        if (getkeystring("Default", "TXBurst",  strtmp, 255, RT2500_SYSTEM_PATH, RT2500_SYSTEM_DATA) == TRUE)
        {
            if (atoi(strtmp) != 0)
                m_bTXBurst = TRUE;
            else
                m_bTXBurst = FALSE;
        }
        else
            m_bTXBurst = FALSE;

        //Get TurboRate value
        if (getkeystring("Default", "TurboRate",  strtmp, 255, RT2500_SYSTEM_PATH, RT2500_SYSTEM_DATA) == TRUE)
        {
            if (atoi(strtmp) != 0)
                m_bTurboRate = TRUE;
            else
                m_bTurboRate = FALSE;
        }
        else
            m_bTurboRate = FALSE;

        // Get ShortSlot value
        if (getkeystring("Default", "ShortSlot",  strtmp, 255, RT2500_SYSTEM_PATH, RT2500_SYSTEM_DATA) == TRUE)
        {
            if (atoi(strtmp) != 0)
                m_bShortSlot = TRUE;
            else
                m_bShortSlot = FALSE;
        }
        else
            m_bShortSlot = FALSE;

        // Get BGProtection value
        if (getkeystring("Default", "BGProtection",  strtmp, 255, RT2500_SYSTEM_PATH, RT2500_SYSTEM_DATA) == TRUE)
        {
            m_nBGProtection = atoi(strtmp);

            if ((m_nBGProtection < 0) || (m_nBGProtection >= 3))
                m_nBGProtection = 0;
        }
        m_nBGProtection = 0;

        // Get TXRate value
        if (getkeystring("Default", "TxRate",  strtmp, 255, RT2500_SYSTEM_PATH, RT2500_SYSTEM_DATA) == TRUE)
        {
            m_nTXRate = atoi(strtmp);
        }

        OidQueryInformation(RT_OID_802_11_STA_CONFIG, m_nSocketId, m_strDeviceName, &configOldStation, sizeof(configOldStation));
        configStation.EnableTurboRate = m_bTurboRate;
        configStation.EnableTxBurst = m_bTXBurst;
        configStation.UseBGProtection = m_nBGProtection;
        configStation.UseShortSlotTime = m_bShortSlot;
        configStation.UseOfdmRatesIn11gAdhoc = m_bAdhocOfdm;
        if(memcmp(&configOldStation, &configStation, sizeof(RT_802_11_STA_CONFIG)) != 0)        
            OidSetInformation(RT_OID_802_11_STA_CONFIG, m_nSocketId, m_strDeviceName, &configStation, sizeof(configStation));

        memset(aryRates, 0x00, sizeof(NDIS_802_11_RATES));
        if (m_WirelessMode == PHY_11A)
        {
            switch (m_nTXRate)
            {
            case 0:
                aryRates[0] = 0x6c; // 54Mbps
                aryRates[1] = 0x60; // 48Mbps
                aryRates[2] = 0x48; // 36Mbps
                aryRates[3] = 0x30; // 24Mbps
                aryRates[4] = 0x24; // 18M
                aryRates[5] = 0x18; // 12M
                aryRates[6] = 0x12; // 9M
                aryRates[7] = 0x0c; // 6M
                break;
            case 1:
                aryRates[0] = 0x0c; // 6M
                break;
            case 2:
                aryRates[0] = 0x12; // 9M
                break;
            case 3:
                aryRates[0] = 0x18; // 12M
                break;
            case 4:
                aryRates[0] = 0x24; // 18M
                break;
            case 5:
                aryRates[0] = 0x30; // 24M
                break;
            case 6:
                aryRates[0] = 0x48; // 36M
                break;
            case 7:
                aryRates[0] = 0x60; // 48M
                break;
            case 8:
                aryRates[0] = 0x6c; // 54M
                break;
            }
        }
        else if ((m_WirelessMode == PHY_11BG_MIXED) || (m_WirelessMode == PHY_11B) ||
                 (m_WirelessMode == PHY_11ABG_MIXED))
        {
            switch(m_nTXRate)
            {
            case 0:
                switch(m_WirelessMode)
                {
                case PHY_11BG_MIXED: // B/G Mixed
                case PHY_11ABG_MIXED: // A/B/G Mixed
                    aryRates[0] = 0x6c; // 54Mbps
                    aryRates[1] = 0x60; // 48Mbps
                    aryRates[2] = 0x48; // 36Mbps
                    aryRates[3] = 0x30; // 24Mbps
                    aryRates[4] = 0x16; // 11Mbps
                    aryRates[5] = 0x0b; // 5.5Mbps
                    aryRates[6] = 0x04; // 2Mbps
                    aryRates[7] = 0x02; // 1Mbps
                    break;
                case PHY_11B: // B Only
                    aryRates[0] = 0x16; // 11Mbps
                    aryRates[1] = 0x0b; // 5.5Mbps
                    aryRates[2] = 0x04; // 2Mbps
                    aryRates[3] = 0x02; // 1Mbps
                    break;
                case PHY_11A:
                    break;   //Not be call, for avoid warning.
                }
                break;
            case 1:
                aryRates[0] = 0x02; // 1M
                break;
            case 2:
                aryRates[0] = 0x04; // 2M
                break;
            case 3:
                aryRates[0] = 0x0b; // 5.5M
                break;
            case 4:
                aryRates[0] = 0x16; // 11M
                break;
            case 5:
                aryRates[0] = 0x0c; // 6M
                break;
            case 6:
                aryRates[0] = 0x12; // 9M
                break;
            case 7:
                aryRates[0] = 0x18; // 12M
                break;
            case 8:
                aryRates[0] = 0x24; // 18M
                break;
            case 9:
                aryRates[0] = 0x30; // 24M
                break;
            case 10:
                aryRates[0] = 0x48; // 36M
                break;
            case 11:
                aryRates[0] = 0x60; // 48M
                break;
            case 12:
                aryRates[0] = 0x6c; // 54M
                break;
            }
        }
        OidSetInformation(OID_802_11_DESIRED_RATES, m_nSocketId, m_strDeviceName, &aryRates, sizeof(NDIS_802_11_RATES));

        OidQueryInformation(OID_802_11_INFRASTRUCTURE_MODE, m_nSocketId, m_strDeviceName, &enumNetworkType, sizeof(enumNetworkType));
        if (ptr->NetworkType != enumNetworkType)
        {
            bSetSSID = TRUE;
            OidSetInformation(OID_802_11_INFRASTRUCTURE_MODE, m_nSocketId, m_strDeviceName, &ptr->NetworkType, sizeof(ptr->NetworkType));
        }
        //Write to Registry
        if (ptr->NetworkType == Ndis802_11IBSS)
            writekeystring("Default", "NetworkType", "Adhoc", RT2500_SYSTEM_PATH, RT2500_SYSTEM_DATA);
        else
            writekeystring("Default", "NetworkType", "Infra", RT2500_SYSTEM_PATH, RT2500_SYSTEM_DATA);

        OidQueryInformation(RT_OID_802_11_PREAMBLE, m_nSocketId, m_strDeviceName, &enumPreamType, sizeof(enumPreamType));
        if (ptr->PreamType != enumPreamType)
            OidSetInformation(RT_OID_802_11_PREAMBLE, m_nSocketId, m_strDeviceName, &ptr->PreamType, sizeof(ptr->PreamType));

        //Write to Registry
        switch (ptr->PreamType)
        {
        case Rt802_11PreambleLong:
            writekeystring("Default", "PreambleType", "Long", RT2500_SYSTEM_PATH, RT2500_SYSTEM_DATA);
            break;
        case Rt802_11PreambleShort:
            writekeystring("Default", "PreambleType", "Short", RT2500_SYSTEM_PATH, RT2500_SYSTEM_DATA);
            break;
        case Rt802_11PreambleAuto:
        default:
            writekeystring("Default", "PreambleType", "Auto", RT2500_SYSTEM_PATH, RT2500_SYSTEM_DATA);
            break;
        }

        OidQueryInformation(OID_802_11_RTS_THRESHOLD, m_nSocketId, m_strDeviceName, &lRtsThre, sizeof(lRtsThre));
        if (ptr->RTS != lRtsThre)
            OidSetInformation(OID_802_11_RTS_THRESHOLD, m_nSocketId, m_strDeviceName, &ptr->RTS, sizeof(ptr->RTS));

        //Write to Registry
        sprintf(strtmp, "%ld", ptr->RTS);
        writekeystring("Default", "RTSThreshold", strtmp, RT2500_SYSTEM_PATH, RT2500_SYSTEM_DATA);

        OidQueryInformation(OID_802_11_FRAGMENTATION_THRESHOLD, m_nSocketId, m_strDeviceName, &lFragThre, sizeof(lFragThre));
        if (ptr->Fragment != lFragThre)
            OidSetInformation(OID_802_11_FRAGMENTATION_THRESHOLD, m_nSocketId, m_strDeviceName, &ptr->Fragment, sizeof(ptr->Fragment));

        //Write to Registry
        sprintf(strtmp, "%ld", ptr->Fragment);
        writekeystring("Default", "FragThreshold", strtmp, RT2500_SYSTEM_PATH, RT2500_SYSTEM_DATA);

        OidQueryInformation(OID_802_11_AUTHENTICATION_MODE, m_nSocketId, m_strDeviceName, &enumAuthenType, sizeof(enumAuthenType));
        if (ptr->Authentication != enumAuthenType)
        {
            bSetSSID = TRUE;
            OidSetInformation(OID_802_11_AUTHENTICATION_MODE, m_nSocketId, m_strDeviceName, &ptr->Authentication, sizeof(ptr->Authentication));
        }

        //Write to Registry
        switch (ptr->Authentication)
        {
        case Ndis802_11AuthModeShared:
            writekeystring("Default", "AuthMode", "SHARED", RT2500_SYSTEM_PATH, RT2500_SYSTEM_DATA);
            break;
        case Ndis802_11AuthModeWPA:
            writekeystring("Default", "AuthMode", "WPA", RT2500_SYSTEM_PATH, RT2500_SYSTEM_DATA);
            break;
        case Ndis802_11AuthModeWPAPSK:
            writekeystring("Default", "AuthMode", "WPAPSK", RT2500_SYSTEM_PATH, RT2500_SYSTEM_DATA);
            break;
        case Ndis802_11AuthModeWPANone:
            writekeystring("Default", "AuthMode", "WPA-None", RT2500_SYSTEM_PATH, RT2500_SYSTEM_DATA);
            break;
        case Ndis802_11AuthModeOpen:
        default:
            writekeystring("Default", "AuthMode", "OPEN", RT2500_SYSTEM_PATH, RT2500_SYSTEM_DATA);
            break;
        }

        OidQueryInformation(OID_802_11_WEP_STATUS, m_nSocketId, m_strDeviceName, &enumEncryp, sizeof(enumEncryp));
        if ( ptr->Encryption != enumEncryp)
        {
            bSetSSID = TRUE;
            OidSetInformation(OID_802_11_WEP_STATUS, m_nSocketId, m_strDeviceName, &ptr->Encryption, sizeof(ptr->Encryption));
        }

        switch (ptr->Encryption)
        {
        case Ndis802_11WEPEnabled:
            writekeystring("Default", "EncrypType", "WEP", RT2500_SYSTEM_PATH, RT2500_SYSTEM_DATA);
            break;
        case Ndis802_11Encryption2Enabled:
            writekeystring("Default", "EncrypType", "TKIP", RT2500_SYSTEM_PATH, RT2500_SYSTEM_DATA);
            break;
        case Ndis802_11Encryption3Enabled:
            writekeystring("Default", "EncrypType", "AES", RT2500_SYSTEM_PATH, RT2500_SYSTEM_DATA);
            break;
        case Ndis802_11WEPDisabled:
        default:
            writekeystring("Default", "EncrypType", "NONE", RT2500_SYSTEM_PATH, RT2500_SYSTEM_DATA);
            break;
        }

        if (ptr->Encryption == Ndis802_11WEPEnabled)
        {
            sprintf(strtmp, "%d", ptr->KeyDefaultId + 1);
            writekeystring("Default", "DefaultKeyID", strtmp, RT2500_SYSTEM_PATH, RT2500_SYSTEM_DATA);
            //Key1
            if (ptr->Key1Type == 0) //hex
                writekeystring("Default", "Key1Type", "0", RT2500_SYSTEM_PATH, RT2500_SYSTEM_DATA);
            else
                writekeystring("Default", "Key1Type", "1", RT2500_SYSTEM_PATH, RT2500_SYSTEM_DATA);
            writekeystring("Default", "Key1Str", ptr->Key1, RT2500_SYSTEM_PATH, RT2500_SYSTEM_DATA);
            //Key2
            if (ptr->Key2Type == 0) //hex
                writekeystring("Default", "Key2Type", "0", RT2500_SYSTEM_PATH, RT2500_SYSTEM_DATA);
            else
                writekeystring("Default", "Key2Type", "1", RT2500_SYSTEM_PATH, RT2500_SYSTEM_DATA);
            writekeystring("Default", "Key2Str", ptr->Key2, RT2500_SYSTEM_PATH, RT2500_SYSTEM_DATA);
            //Key3
            if (ptr->Key3Type == 0) //hex
                writekeystring("Default", "Key3Type", "0", RT2500_SYSTEM_PATH, RT2500_SYSTEM_DATA);
            else
                writekeystring("Default", "Key3Type", "1", RT2500_SYSTEM_PATH, RT2500_SYSTEM_DATA);
            writekeystring("Default", "Key3Str", ptr->Key2, RT2500_SYSTEM_PATH, RT2500_SYSTEM_DATA);
            //Key4
            if (ptr->Key4Type == 0) //hex
                writekeystring("Default", "Key4Type", "0", RT2500_SYSTEM_PATH, RT2500_SYSTEM_DATA);
            else
                writekeystring("Default", "Key4Type", "1", RT2500_SYSTEM_PATH, RT2500_SYSTEM_DATA);
            writekeystring("Default", "Key4Str", ptr->Key4, RT2500_SYSTEM_PATH, RT2500_SYSTEM_DATA);

            //----------------------------------------------------------//
            //Key 1
            //----------------------------------------------------------//
            nKeyLen = strlen(ptr->Key1);
            if(nKeyLen == 0)
            {
                removeKey.Length = sizeof(NDIS_802_11_REMOVE_KEY);
                removeKey.KeyIndex = 0;
                for(int i = 0; i < 6; i++)
                    removeKey.BSSID[i] = 0xff;
                OidSetInformation(OID_802_11_REMOVE_KEY, m_nSocketId, m_strDeviceName, &removeKey, removeKey.Length);
            }
            else
            {
                if(nKeyLen == 10)
                    nKeyLen = 5;
                else if(nKeyLen == 26)
                    nKeyLen = 13;

                lBufLen = sizeof(NDIS_802_11_KEY) + nKeyLen - 1;
                // Allocate Resource
                pKey = (PNDIS_802_11_KEY)malloc(lBufLen);
                pKey->Length = lBufLen;
                pKey->KeyLength = nKeyLen;
                pKey->KeyIndex = 0;
                if(ptr->KeyDefaultId == 0)
                    pKey->KeyIndex |= 0x80000000;
                for(i = 0; i < 6; i++)
                    pKey->BSSID[i] = 0xff;

                if(strlen(ptr->Key1) == 5)
                    memcpy(pKey->KeyMaterial, ptr->Key1, 5);
                else if(strlen(ptr->Key1) == 10)
                    AtoH(ptr->Key1, pKey->KeyMaterial, 5);
                else if(strlen(ptr->Key1) == 13)
                    memcpy(pKey->KeyMaterial, ptr->Key1, 13);
                else if(strlen(ptr->Key1) == 26)
                    AtoH(ptr->Key1, pKey->KeyMaterial, 13);

                OidSetInformation(OID_802_11_ADD_KEY, m_nSocketId, m_strDeviceName, pKey, pKey->Length);
                free(pKey);
            }
            //----------------------------------------------------------//
            //Key 2
            //----------------------------------------------------------//
            nKeyLen = strlen(ptr->Key2);
            if(nKeyLen == 0)
            {
                removeKey.Length = sizeof(NDIS_802_11_REMOVE_KEY);
                removeKey.KeyIndex = 1;
                for(int i = 0; i < 6; i++)
                    removeKey.BSSID[i] = 0xff;
                OidSetInformation(OID_802_11_REMOVE_KEY, m_nSocketId, m_strDeviceName, &removeKey, removeKey.Length);
            }
            else
            {
                if(nKeyLen == 10)
                    nKeyLen = 5;
                else if(nKeyLen == 26)
                    nKeyLen = 13;

                lBufLen = sizeof(NDIS_802_11_KEY) + nKeyLen - 1;
                // Allocate Resource
                pKey = (PNDIS_802_11_KEY)malloc(lBufLen);
                pKey->Length = lBufLen;
                pKey->KeyLength = nKeyLen;
                pKey->KeyIndex = 1;
                if(ptr->KeyDefaultId == 1)
                    pKey->KeyIndex |= 0x80000000;
                for(i = 0; i < 6; i++)
                    pKey->BSSID[i] = 0xff;

                if(strlen(ptr->Key2) == 5)
                    memcpy(pKey->KeyMaterial, ptr->Key2, 5);
                else if(strlen(ptr->Key2) == 10)
                    AtoH(ptr->Key2, pKey->KeyMaterial, 5);
                else if(strlen(ptr->Key2) == 13)
                    memcpy(pKey->KeyMaterial, ptr->Key2, 13);
                else if(strlen(ptr->Key2) == 26)
                    AtoH(ptr->Key2, pKey->KeyMaterial, 13);

                OidSetInformation(OID_802_11_ADD_KEY, m_nSocketId, m_strDeviceName, pKey, pKey->Length);
                free(pKey);
            }
            //----------------------------------------------------------//
            //Key 3
            //----------------------------------------------------------//
            nKeyLen = strlen(ptr->Key3);
            if(nKeyLen == 0)
            {
                removeKey.Length = sizeof(NDIS_802_11_REMOVE_KEY);
                removeKey.KeyIndex = 2;
                for(int i = 0; i < 6; i++)
                    removeKey.BSSID[i] = 0xff;
                OidSetInformation(OID_802_11_REMOVE_KEY, m_nSocketId, m_strDeviceName, &removeKey, removeKey.Length);
            }
            else
            {
                if(nKeyLen == 10)
                    nKeyLen = 5;
                else if(nKeyLen == 26)
                    nKeyLen = 13;

                lBufLen = sizeof(NDIS_802_11_KEY) + nKeyLen - 1;
                // Allocate Resource
                pKey = (PNDIS_802_11_KEY)malloc(lBufLen);
                pKey->Length = lBufLen;
                pKey->KeyLength = nKeyLen;
                pKey->KeyIndex = 2;
                if(ptr->KeyDefaultId == 2)
                    pKey->KeyIndex |= 0x80000000;
                for(i = 0; i < 6; i++)
                    pKey->BSSID[i] = 0xff;

                if(strlen(ptr->Key3) == 5)
                    memcpy(pKey->KeyMaterial, ptr->Key3, 5);
                else if(strlen(ptr->Key3) == 10)
                    AtoH(ptr->Key3, pKey->KeyMaterial, 5);
                else if(strlen(ptr->Key3) == 13)
                    memcpy(pKey->KeyMaterial, ptr->Key3, 13);
                else if(strlen(ptr->Key3) == 26)
                    AtoH(ptr->Key3, pKey->KeyMaterial, 13);

                OidSetInformation(OID_802_11_ADD_KEY, m_nSocketId, m_strDeviceName, pKey, pKey->Length);
                free(pKey);
            }
            //----------------------------------------------------------//
            //Key 4
            //----------------------------------------------------------//
            nKeyLen = strlen(ptr->Key4);
            if(nKeyLen == 0)
            {
                removeKey.Length = sizeof(NDIS_802_11_REMOVE_KEY);
                removeKey.KeyIndex = 3;
                for(int i = 0; i < 6; i++)
                    removeKey.BSSID[i] = 0xff;
                OidSetInformation(OID_802_11_REMOVE_KEY, m_nSocketId, m_strDeviceName, &removeKey, removeKey.Length);
            }
            else
            {
                if(nKeyLen == 10)
                    nKeyLen = 5;
                else if(nKeyLen == 26)
                    nKeyLen = 13;

                lBufLen = sizeof(NDIS_802_11_KEY) + nKeyLen - 1;
                // Allocate Resource
                pKey = (PNDIS_802_11_KEY)malloc(lBufLen);
                pKey->Length = lBufLen;
                pKey->KeyLength = nKeyLen;
                pKey->KeyIndex = 3;
                if(ptr->KeyDefaultId == 3)
                    pKey->KeyIndex |= 0x80000000;
                for(i = 0; i < 6; i++)
                    pKey->BSSID[i] = 0xff;

                if(strlen(ptr->Key4) == 5)
                    memcpy(pKey->KeyMaterial, ptr->Key4, 5);
                else if(strlen(ptr->Key4) == 10)
                    AtoH(ptr->Key4, pKey->KeyMaterial, 5);
                else if(strlen(ptr->Key4) == 13)
                    memcpy(pKey->KeyMaterial, ptr->Key3, 13);
                else if(strlen(ptr->Key4) == 26)
                    AtoH(ptr->Key4, pKey->KeyMaterial, 13);

                OidSetInformation(OID_802_11_ADD_KEY, m_nSocketId, m_strDeviceName, pKey, pKey->Length);
                free(pKey);
            }
        }
        else if (ptr->Authentication == Ndis802_11AuthModeWPAPSK)
        {
            writekeystring("Default", "WPAPSK", ptr->WpaPsk, RT2500_SYSTEM_PATH, RT2500_SYSTEM_DATA);

            nKeyLen = 32;
            lBufLen = (sizeof(NDIS_802_11_KEY) + nKeyLen - 1);
            // Allocate Resouce
            pKey = (PNDIS_802_11_KEY)malloc(lBufLen); // Don't use GMEM_ZEROINIT to get random key
            pKey->Length = lBufLen;
            pKey->KeyLength = nKeyLen;
            pKey->KeyIndex = 0x80000000;

            PasswordHash(ptr->WpaPsk, ptr->SSID, ptr->SsidLen, keyMaterial);
            memcpy(pKey->KeyMaterial, keyMaterial, 32);

            OidSetInformation(RT_OID_802_11_ADD_WPA, m_nSocketId, m_strDeviceName, pKey, pKey->Length);

            free(pKey);
        }

        if (ptr->NetworkType == Ndis802_11IBSS)
        {
            OidQueryInformation(OID_802_11_CONFIGURATION, m_nSocketId, m_strDeviceName, &Configuration, sizeof(Configuration));
            for(i = 0; i < G_nChanFreqCount; i++)
            {
                if(ptr->Channel == ChannelFreqTable[i].lChannel)
                {
                    lFreq = ChannelFreqTable[i].lFreq;
                    break;
                }
            }

            if(lFreq != Configuration.DSConfig)
            {
                bSetSSID = TRUE;
                Configuration.DSConfig = lFreq;

                OidSetInformation(OID_802_11_CONFIGURATION, m_nSocketId, m_strDeviceName, &Configuration, sizeof(Configuration));
            }
            //Write to Registry
            //Channel
            sprintf(strtmp, "%d", ptr->Channel);
            writekeystring("Default", "Channel", strtmp, RT2500_SYSTEM_PATH, RT2500_SYSTEM_DATA);
            //Power Save Mode
            writekeystring("Default", "PSMode", "", RT2500_SYSTEM_PATH, RT2500_SYSTEM_DATA);
        }
        else
        { //Infra
            OidQueryInformation(OID_802_11_POWER_MODE, m_nSocketId, m_strDeviceName, &enumPSMode, sizeof(enumPSMode));
            if (ptr->PSmode != enumPSMode)
                OidSetInformation(OID_802_11_POWER_MODE, m_nSocketId, m_strDeviceName, &ptr->PSmode, sizeof(ptr->PSmode));

            writekeystring("Default", "Channel", "0", RT2500_SYSTEM_PATH, RT2500_SYSTEM_DATA);

            //Power Save Mode
            switch (ptr->PSmode)
            {
            case Ndis802_11PowerModeMAX_PSP:
                writekeystring("Default", "PSMode", "MAX_PSP", RT2500_SYSTEM_PATH, RT2500_SYSTEM_DATA);
                break;
            case Ndis802_11PowerModeFast_PSP:
                writekeystring("Default", "PSMode", "Fast_PSP", RT2500_SYSTEM_PATH, RT2500_SYSTEM_DATA);
                break;
            case Ndis802_11PowerModeCAM:
            default:
                writekeystring("Default", "PSMode", "CAM", RT2500_SYSTEM_PATH, RT2500_SYSTEM_DATA);
            }
        }

        OidQueryInformation(OID_802_11_SSID, m_nSocketId, m_strDeviceName, &SSID, sizeof(SSID));
        memset(strSSID, 0x00, NDIS_802_11_LENGTH_SSID + 1);
        memcpy(strSSID, SSID.Ssid, SSID.SsidLength);

        if (bSetSSID || (strcmp((const char *)ptr->SSID, strSSID) != 0))
        {
            memset(&SSID, 0x00, sizeof(NDIS_802_11_SSID));
            SSID.SsidLength = ptr->SsidLen;
            memcpy(SSID.Ssid, (const void *)ptr->SSID, ptr->SsidLen);

            OidSetInformation(OID_802_11_SSID, m_nSocketId, m_strDeviceName, &SSID, sizeof(SSID));
        }
    }

}

void RaConfigForm::Profile_OnAddProfile()
{

    AddProfileDlg                   *pAddProfileDlg;

    killTimer(timerId_UpdateProfileStatus);
    timerId_UpdateProfileStatus = -1;

    pAddProfileDlg = new AddProfileDlg(m_nSocketId, m_strDeviceName, this, "AddProfile", PROFILE_ADD, Profile_ListView, &m_pProfileSetting, NULL, TRUE);
    pAddProfileDlg->exec();

    if (pAddProfileDlg->IsOk())
    {
        Profile_WriteProfileToFile();

        if (Profile_ListView->childCount() == 0 )
        {
            Profile_PushButton_Delete->setEnabled(FALSE);
            Profile_PushButton_Edit->setEnabled(FALSE);
            Profile_PushButton_Activate->setEnabled(FALSE);
        }
        else
        {
            Profile_PushButton_Delete->setEnabled(TRUE);
            Profile_PushButton_Edit->setEnabled(TRUE);
            Profile_PushButton_Activate->setEnabled(TRUE);
        }
    }
    delete pAddProfileDlg;
    timerId_UpdateProfileStatus = startTimer(2000);
}

void RaConfigForm::Profile_OnDeleteProfile()
{
    QListViewItem                   *Item;
    QString                         qstr;
    PRT_PROFILE_SETTING             ptr;
    PRT_PROFILE_SETTING             previous;
    int                             answer = 0;

    killTimer(timerId_UpdateProfileStatus);
    timerId_UpdateProfileStatus = -1;

    Item = Profile_ListView->currentItem();
    if (Item == NULL)
    {
        timerId_UpdateProfileStatus = startTimer(2000);
        return ;  //No one selected!
    }

    qstr=Item->text(0);
    if (qstrcmp(qstr.data(), m_strActiveProfileID) == 0)
    {
        answer = QMessageBox::warning(this, "Warning", "The profile which you want to delete is in active!",
            "&Yes", "&No", QString::null, 1, 1 );
        if ( answer == 0 ) 
        { //Yes
            memset(m_strActiveProfileID, 0x00, 32+1);
            writekeystring("Default", "ProfileID", "", RT2500_SYSTEM_PATH, RT2500_SYSTEM_DATA);
            writekeystring("Default", "SSID", "", RT2500_SYSTEM_PATH, RT2500_SYSTEM_DATA);
        }
        else
        {
            timerId_UpdateProfileStatus = startTimer(2000);
            return;  //do nothing.
        }
    }

    ptr = m_pProfileSetting;
    previous = ptr;
    while (ptr!=NULL)
    {
        if (qstr.compare((const char *)ptr->Profile) == 0)
        {
            if (ptr == m_pProfileSetting)
            {
                m_pProfileSetting = m_pProfileSetting->Next;
                free (ptr);
            }
            else
            {
                previous->Next = ptr->Next;
                free(ptr);
            }
            Profile_ListView->takeItem(Item);
            break;
        }
        else
            previous = ptr;
        ptr = ptr->Next;
    }

    Profile_WriteProfileToFile();

    if (G_bUserAdmin)
    {
        if (Profile_ListView->childCount() == 0 )
        {
            Profile_PushButton_Delete->setEnabled(FALSE);
            Profile_PushButton_Edit->setEnabled(FALSE);
            Profile_PushButton_Activate->setEnabled(FALSE);
        }
        else
        {
            Profile_PushButton_Delete->setEnabled(TRUE);
            Profile_PushButton_Edit->setEnabled(TRUE);
            Profile_PushButton_Activate->setEnabled(TRUE);
        }
    }
    timerId_UpdateProfileStatus = startTimer(2000);
}

void RaConfigForm::Profile_OnEditProfile()
{
    AddProfileDlg                   *pAddProfileDlg;
    QListViewItem                   *Item;
    QString                         qstr;
    bool                            bChangeProfileName = FALSE;

    if (!G_bUserAdmin)
    {
        QMessageBox::information(this, "Information", "You do not have root privilege!");
        return;
    }

    Item = Profile_ListView->currentItem();
    if (Item == NULL)
    {
        QMessageBox::warning(this, "Warning", "Please select profile first.!");
        return;
    }

    killTimer(timerId_UpdateProfileStatus);
    timerId_UpdateProfileStatus = -1;

    qstr=Item->text(0);
    if (strcmp(qstr.data(), m_strActiveProfileID) == 0)
        bChangeProfileName = TRUE;

    pAddProfileDlg = new AddProfileDlg(m_nSocketId, m_strDeviceName, this, "AddProfile", PROFILE_EDIT, Profile_ListView, &m_pProfileSetting, NULL, TRUE);
    pAddProfileDlg->exec();
    
    if (pAddProfileDlg->IsOk())
    {
        Profile_WriteProfileToFile();

        if (Profile_ListView->childCount() == 0 )
        {
            Profile_PushButton_Delete->setEnabled(FALSE);
            Profile_PushButton_Edit->setEnabled(FALSE);
            Profile_PushButton_Activate->setEnabled(FALSE);
        }
        else
        {
            Profile_PushButton_Delete->setEnabled(TRUE);
            Profile_PushButton_Edit->setEnabled(TRUE);
            Profile_PushButton_Activate->setEnabled(TRUE);
        }

        if (bChangeProfileName)
        {
            Profile_WriteConfigToRegistryAndSetOid();
            killTimer(timerId_UpdateProfileStatus);
            timerId_UpdateProfileStatus = -1;
            timerId_UpdateProfileStatus = startTimer(2000);
            m_bUpdateSiteSurveyPage = TRUE;
            m_bUpdateLinkSatusPage = TRUE;
        }
    }

    delete pAddProfileDlg;
    timerId_UpdateProfileStatus = startTimer(2000);
}

void RaConfigForm::Profile_OnActive()
{
    killTimer(timerId_UpdateProfileStatus);
    // Stop SiteSurvey Autoreconnect
    m_bSetBssid = FALSE;
    m_bSetSsid = FALSE;
    timerId_UpdateProfileStatus = -1;
    timerId_UpdateProfileStatus = startTimer(2000);
}

void RaConfigForm::Profile_OnActiveProfile()
{
    QListViewItem                   *Item;

    Item = Profile_ListView->currentItem();
    if (Item == NULL)
    {
        QMessageBox::warning(this, "Warning", "Please select profile first.!");
        return;
    }

    Profile_WriteConfigToRegistryAndSetOid();

    killTimer(timerId_UpdateProfileStatus);
    timerId_UpdateProfileStatus = -1;
    timerId_UpdateProfileStatus = startTimer(2000);
    m_bUpdateSiteSurveyPage = TRUE;
    m_bUpdateLinkSatusPage = TRUE;
}

void RaConfigForm::SiteSurvey_OnActive()
{
    m_bRescan = TRUE;
    SiteSurvey_ProbeConnectStatus();
    timerId_ConnectStatus = startTimer(2000);
}

void RaConfigForm::SiteSurvey_ProbeConnectStatus()
{
    NDIS_MEDIA_STATE            ConnectStatus = NdisMediaStateDisconnected;
    NDIS_802_11_SSID            SsidQuery;
    NDIS_802_11_MAC_ADDRESS     BssidQuery;
    char                        strSSID[NDIS_802_11_LENGTH_SSID + 1];
    char                        msg[255];

    if (m_bRescan)
    {
        SiteSurvey_RescanTimerFunc();
        m_bRescan = FALSE;
    }

    if (OidQueryInformation(OID_GEN_MEDIA_CONNECT_STATUS, m_nSocketId, m_strDeviceName, &ConnectStatus, sizeof(ConnectStatus)) >= 0)
    {
        if(ConnectStatus == NdisMediaStateConnected && G_bRadio)
        {
            m_nTimerCount = 0;
            m_bRescan = TRUE;        

            memset(&SsidQuery, 0x00, sizeof(SsidQuery));
            OidQueryInformation(OID_802_11_SSID, m_nSocketId, m_strDeviceName, &SsidQuery, sizeof(SsidQuery));        

            if (SsidQuery.SsidLength == 0)
            {
                memset(&BssidQuery, 0x00, sizeof(BssidQuery));
                OidQueryInformation(OID_802_11_BSSID, m_nSocketId, m_strDeviceName, &BssidQuery, sizeof(BssidQuery));
                sprintf(msg, "Connected <--> [%02X:%02X:%02X:%02X:%02X:%02X]", 
                                            BssidQuery[0], BssidQuery[1], BssidQuery[2], 
                                            BssidQuery[3], BssidQuery[4], BssidQuery[5]);
            }
            else
            {
                memset(strSSID, 0x00, NDIS_802_11_LENGTH_SSID + 1);
                memcpy(strSSID, SsidQuery.Ssid, SsidQuery.SsidLength);
                sprintf(msg, "Connected <--> %s", strSSID);
            }

            SiteSurvey_LineEdit_Status->setText(msg);
        }
        else
        {
            if (G_bRadio)
            {
                if (m_nTimerCount == 1)
                    m_bRescan = TRUE;
                if ((m_nTimerCount % 30) == 0)
                    OidSetInformation(OID_802_11_BSSID_LIST_SCAN, m_nSocketId, m_strDeviceName, 0, 0);
                else
                {
                    SiteSurvey_LineEdit_Status->setText("Disconnected");
                    // if Site Survey connect failed then try reconnect
                    if (m_bSetSsid)
                        OidSetInformation(OID_802_11_SSID, m_nSocketId, m_strDeviceName, &m_SsidSet, sizeof(m_SsidSet));        
                    else if (m_bSetBssid)
                    {
                        OidSetInformation(OID_802_11_BSSID, m_nSocketId, m_strDeviceName, &m_BssidSet, sizeof(m_BssidSet));        
                        if(m_nTimerCount >= 5)
                        {
                            m_bSetBssid = FALSE;
                            m_bSetSsid = TRUE;
                        }
                    }
                }
                m_nTimerCount++;
            }
            else
                SiteSurvey_LineEdit_Status->setText("Radio Status <--> OFF");
        }
    }
    else
        SiteSurvey_LineEdit_Status->setText("Disconnected");


    SiteSurvey_UpdateConnectStatus(ConnectStatus);
}

void RaConfigForm::SiteSurvey_OnRescan()
{
    killTimer(timerId_ConnectStatus);
    timerId_ConnectStatus = -1;

    SiteSurvey_LineEdit_Status->setText("Rescanning");

    SiteSurvey_PushButton_Rescan->setEnabled(FALSE);
    SiteSurvey_PushButton_Connect->setEnabled(FALSE);
    SiteSurvey_PushButton_AddProfile->setEnabled(FALSE);

    OidSetInformation(OID_802_11_BSSID_LIST_SCAN, m_nSocketId, m_strDeviceName, 0, 0);    
    timerId_ConnectStatus = startTimer(2000);
    m_bRescan = TRUE;
}

void RaConfigForm::SiteSurvey_RescanTimerFunc()
{
    QListViewItem           *ListItem;
    PNDIS_WLAN_BSSID_EX     pBssid;
    char                    strSSID[NDIS_802_11_LENGTH_SSID + 1];    
    QString                 qstrBssid;
    QString                 qstrRSSI;
    QString                 qstrChannel;
    ULONG                   lBufLen = 65536; // 64K
    ULONG                   i;
    UINT                    nSigQua;
    int                     nChannel;
    int                     j;

    SiteSurvey_ListView->clear();

    if (OidQueryInformation(OID_802_11_BSSID_LIST, m_nSocketId, m_strDeviceName, m_pBssidList, lBufLen) < 0)
    { //failed
        memset(m_pBssidList, 0x00, lBufLen);
        return;
    }

    pBssid = (PNDIS_WLAN_BSSID_EX) m_pBssidList->Bssid;
    for (i = 0; i < m_pBssidList->NumberOfItems; i++)
    {
        memset(strSSID, 0x00, NDIS_802_11_LENGTH_SSID + 1);
        memcpy(strSSID, pBssid->Ssid.Ssid, pBssid->Ssid.SsidLength);

        qstrBssid.sprintf("%02X-%02X-%02X-%02X-%02X-%02X", 
                        pBssid->MacAddress[0], pBssid->MacAddress[1], pBssid->MacAddress[2],
                        pBssid->MacAddress[3], pBssid->MacAddress[4], pBssid->MacAddress[5]);

        nSigQua = ConvertRssiToSignalQuality(pBssid->Rssi);

        qstrRSSI.sprintf("%d%%", nSigQua);

        nChannel = -1;

        for(j = 0; j < G_nChanFreqCount; j++)
        {
            if(pBssid->Configuration.DSConfig == ChannelFreqTable[j].lFreq)
            {
                nChannel = ChannelFreqTable[j].lChannel;
                break;
            }
        }

        if(nChannel == -1)
            continue;

        qstrChannel.sprintf("%u", nChannel);

        // Insert the item, select every other item.        
        ListItem=new QListViewItem(SiteSurvey_ListView);
        // Set subitem 0
        ListItem->setPixmap(0, uic_load_pixmap_RaConfigForm("uncheck16.xpm"));
        ListItem->setText(0, strSSID);
        // Set subitem 1
        ListItem->setText(1, qstrBssid);
        // Set subitem 2
        ListItem->setText(2, qstrRSSI);
        // Set subitem 3
        ListItem->setText(3, qstrChannel);
        // Set subitem 4
        if (pBssid->Privacy)
            ListItem->setText(4, strAryEncryption[0]);
        else
            ListItem->setText(4, strAryEncryption[1]);
        // Set subitem 5
        ListItem->setText(5, "Unknown");
        // Set subitem 6        
        ListItem->setText(6, strAryNetworkType[pBssid->InfrastructureMode]);

        // work with NDIS_WLAN_BSSID_EX
        if ((pBssid->Length > sizeof(NDIS_WLAN_BSSID)) && (pBssid->IELength > sizeof(NDIS_802_11_FIXED_IEs)))
        {
            ULONG lIELoc = 0;
            PNDIS_802_11_FIXED_IEs pFixIE = (PNDIS_802_11_FIXED_IEs)pBssid->IEs;
            PNDIS_802_11_VARIABLE_IEs pVarIE = (PNDIS_802_11_VARIABLE_IEs)((char*)pFixIE + sizeof(NDIS_802_11_FIXED_IEs));
            lIELoc += sizeof(NDIS_802_11_FIXED_IEs);
            while (pBssid->IELength > (lIELoc + sizeof(NDIS_802_11_VARIABLE_IEs)))
            {
                if ((pVarIE->ElementID == 221) && (pVarIE->Length >= 16))
                {
                    ULONG* pOUI = (ULONG*)((char*)pVarIE + 2);
                    if(*pOUI != WPA_OUI_TYPE)
                        break;
                    ULONG* plGroupKey; 
                    WORD* pdPairKeyCount;
                    ULONG* plAuthenKey; 
                    WORD* pdAuthenKeyCount;
                    plGroupKey = (ULONG*)((char*)pVarIE + 8);

                    ULONG lGroupKey = *plGroupKey & 0x00ffffff;
                    if (lGroupKey == WPA_OUI)
                    {
                        lGroupKey = (*plGroupKey & 0xff000000) >> 0x18;
                        if (lGroupKey == 2)
                            ListItem->setText(4, "TKIP");
                        else if (lGroupKey == 3)
                            ListItem->setText(4, "AES-WRAP");
                        else if (lGroupKey == 4)
                            ListItem->setText(4, "AES-CCMP");
                    }
                    else
                        break;

                    pdPairKeyCount = (WORD*)((char*)plGroupKey + 4);
                    pdAuthenKeyCount = (WORD*)((char*)pdPairKeyCount + 2 + 4 * (*pdPairKeyCount));
                    if (*pdAuthenKeyCount > 0)
                    {
                        plAuthenKey = (ULONG*)((char*)pdAuthenKeyCount + 2);

                        ULONG lAuthenKey = *plAuthenKey & 0x00ffffff;
                        if (lAuthenKey == WPA_OUI)
                        {
                            lAuthenKey = (*plAuthenKey & 0xff000000) >> 0x18;
                            if (lAuthenKey == 1)
                                ListItem->setText(5, "WPA");
                            else if (lAuthenKey == 2)
                            {
                                if (pBssid->InfrastructureMode)
                                    ListItem->setText(5, "WPAPSK");
                                else 
                                    ListItem->setText(5, "WPA-None");
                            }
                        }
                    }
                    break;
                }
                lIELoc += pVarIE->Length;
                pVarIE = (PNDIS_802_11_VARIABLE_IEs)((char*)pVarIE + pVarIE->Length);
                
                if(pVarIE->Length <= 0)
                    break;
            }
        }
        pBssid = (PNDIS_WLAN_BSSID_EX)((char *)pBssid + pBssid->Length);
    }
}

bool RaConfigForm::SiteSurvey_ResetOidValue(NDIS_802_11_NETWORK_INFRASTRUCTURE enumInfrastructureMode)
{
    RT_802_11_PREAMBLE                      enumPreamType = Rt802_11PreambleAuto;
    NDIS_802_11_RTS_THRESHOLD               lRtsThre = MAX_RTS_THRESHOLD;
    NDIS_802_11_FRAGMENTATION_THRESHOLD     lFragThre = 0;
    NDIS_802_11_TX_POWER_LEVEL              lTransPower = MAX_TX_POWER_LEVEL;
    NDIS_802_11_POWER_MODE                  enumPSMode = Ndis802_11PowerModeCAM;

    OidSetInformation(RT_OID_802_11_PREAMBLE, m_nSocketId, m_strDeviceName, &enumPreamType, sizeof(enumPreamType));

    OidSetInformation(OID_802_11_TX_POWER_LEVEL, m_nSocketId, m_strDeviceName, &lTransPower, sizeof(lTransPower));

    OidSetInformation(OID_802_11_RTS_THRESHOLD, m_nSocketId, m_strDeviceName, &lRtsThre, sizeof(lRtsThre));

    OidSetInformation(OID_802_11_FRAGMENTATION_THRESHOLD, m_nSocketId, m_strDeviceName, &lFragThre, sizeof(lFragThre));

    if (enumInfrastructureMode == Ndis802_11Infrastructure)
    {
        OidSetInformation(OID_802_11_POWER_MODE, m_nSocketId, m_strDeviceName, &enumPSMode, sizeof(enumPSMode));
    }
    else if (enumInfrastructureMode == Ndis802_11IBSS)
    {
        ; //do nothing
    }

    return TRUE;
}

void RaConfigForm::SiteSurvey_UpdateConnectStatus(NDIS_MEDIA_STATE ConnectStatus)
{
    QListViewItem       *ListItem;
    QString                     qstrBssid;
    NDIS_802_11_MAC_ADDRESS     BssidQuery;
    NDIS_802_11_MAC_ADDRESS     Bssid;
    int                 nItem;
    int                         i,j;


    memset(&BssidQuery, 0x00, sizeof(BssidQuery));
    OidQueryInformation(OID_802_11_BSSID, m_nSocketId, m_strDeviceName, &BssidQuery, sizeof(BssidQuery));

    nItem = SiteSurvey_ListView->childCount();
    ListItem = SiteSurvey_ListView->firstChild();
    for (i = 0; i < nItem; i++)
    {
        ListItem->setPixmap(0, uic_load_pixmap_RaConfigForm("uncheck16.xpm"));
        if(ConnectStatus == NdisMediaStateConnected && G_bRadio)
        {
            qstrBssid = ListItem->text(1);
            j = 0;
            while ( ( j = qstrBssid.find( '-', j ) ) != -1 )
                qstrBssid.remove( j ,1 );

            AtoH((char *)qstrBssid.data(), Bssid, 6);
            if(memcmp(BssidQuery, Bssid, 6) == 0)
            {
                ListItem->setPixmap(0, uic_load_pixmap_RaConfigForm("handshak16.xpm"));
                m_bRescan = FALSE;
            }
        }
        ListItem = ListItem->itemBelow();
    }

    if (m_bUpdateProfilePage)
    {
        m_bUpdateProfilePage = FALSE;
        Profile_UpdateProfileStatus();
    }

    if (m_bUpdateLinkSatusPage)
    {
        m_bUpdateLinkSatusPage = FALSE;
        LinkStatus_UpdateStatus();
    }

}

void RaConfigForm::SiteSurvey_OnConnect()
{
    QListViewItem                           *CurSelItem;
    PNDIS_WLAN_BSSID_EX                     pBssid;
    NDIS_802_11_MAC_ADDRESS                 CurBssid;
    NDIS_802_11_AUTHENTICATION_MODE         AuthenticationMode = Ndis802_11AuthModeOpen;
    NDIS_802_11_ENCRYPTION_STATUS           EncryptType = Ndis802_11WEPDisabled;
    NDIS_802_11_AUTHENTICATION_MODE         EncryStatus;
    NDIS_802_11_REMOVE_KEY                  removeKey;
    PNDIS_802_11_KEY                        pKey = NULL;
    QString                                 qstrAuthen;
    QString                                 qstrEncrypt;
    QString                                 qstrBssid;
    QString                                 strPsk;
    QString                                 strKey;
    ULONG                                   index;
    ULONG                                   nKeyLen;
    ULONG                                   lBufLen;
    UCHAR                                   keyMaterial[40];
    int                                     i = 0;
    bool                                    bfound = FALSE;
    bool                                    bHiddenSsid = FALSE;

    if (!G_bUserAdmin)
    {
        QMessageBox::information(this, "Information", "You do not have root privilege!");
        return;
    }

    CurSelItem = SiteSurvey_ListView->selectedItem();
    if(!CurSelItem)
    {
        QMessageBox::warning(this, "Warning", "No selected Item!");
        return;
    }

    if (!m_pBssidList)
        return;

    // Not support WPA yet
    EncryStatus = SiteSurvey_GetEncryStatus();
    if (EncryStatus == Ndis802_11AuthModeWPA)
        return;

    killTimer(timerId_ConnectStatus);
    timerId_ConnectStatus = -1;

    qstrBssid = CurSelItem->text(1);
    while ( ( i = qstrBssid.find( '-', i ) ) != -1 )
        qstrBssid.remove( i ,1 );

    AtoH((char *)qstrBssid.data(), CurBssid, 6);

    pBssid = (PNDIS_WLAN_BSSID_EX)m_pBssidList->Bssid;
    //for (i = 0; i < m_nCurSelItem; i++)
    for (index = 0; index < m_pBssidList->NumberOfItems; index++)
    {
        if(memcmp(pBssid->MacAddress, CurBssid, 6) == 0)
        {
            bfound = TRUE;
            break;
        }
        pBssid = (PNDIS_WLAN_BSSID_EX)((char *)pBssid + pBssid->Length);
    }

    if (!bfound)
        return;

    if (pBssid->Ssid.SsidLength == 0)
    {
        HiddenSsidDlg *pHiddendlg = new HiddenSsidDlg(this, "HiddenSsid", TRUE);
        QString qstrSsid;

        pHiddendlg->exec();
        if (pHiddendlg->IsClickOk())
        {
            bHiddenSsid = TRUE;
            qstrSsid = pHiddendlg->GetSsidString();
            m_SsidSet.SsidLength = qstrSsid.length();
            memcpy(m_SsidSet.Ssid, qstrSsid.data(), m_SsidSet.SsidLength);
        }
        else
            return;
    }

    // Reset all configuration value
    SiteSurvey_ResetOidValue(pBssid->InfrastructureMode);

    // Set Infrastructure Mode
    OidSetInformation(OID_802_11_INFRASTRUCTURE_MODE, m_nSocketId, m_strDeviceName, &pBssid->InfrastructureMode, sizeof(pBssid->InfrastructureMode));

    // Set Wep Status
    if (pBssid->Privacy)
    {
        AuthSecuDlg *pAuthSecuDlg = new AuthSecuDlg(this, "AuthSecuDlg", TRUE);

        qstrAuthen = CurSelItem->text(5);
        qstrEncrypt = CurSelItem->text(4);

        if (qstrAuthen.compare("Unknown") == 0)
        {
            if (qstrEncrypt.compare("WEP") == 0)
            {
                EncryptType = Ndis802_11WEPEnabled;
                AuthenticationMode = Ndis802_11AuthModeOpen;
            }
        }
        else if (qstrAuthen.compare("WPAPSK") == 0)
        {
            AuthenticationMode = Ndis802_11AuthModeWPAPSK;
            if (qstrEncrypt.compare("TKIP") == 0)
                EncryptType = Ndis802_11Encryption2Enabled;
            else if (qstrEncrypt.compare("AES-WRAP") == 0)
                EncryptType = Ndis802_11Encryption3Enabled;
            else if (qstrEncrypt.compare("AES-CCMP") == 0)
                EncryptType = Ndis802_11Encryption3Enabled;
        }
        else if (qstrAuthen.compare("WPA-None") == 0)
        {
            AuthenticationMode = Ndis802_11AuthModeWPANone;
            if (qstrEncrypt.compare("TKIP") == 0)
                EncryptType = Ndis802_11Encryption2Enabled;
            else if (qstrEncrypt.compare("AES-WRAP") == 0)
                EncryptType = Ndis802_11Encryption3Enabled;
            else if (qstrEncrypt.compare("AES-CCMP") == 0)
                EncryptType = Ndis802_11Encryption3Enabled;
        }
        else if (qstrAuthen.compare("WPA") == 0)
        {
            AuthenticationMode = Ndis802_11AuthModeWPA;
            if (qstrEncrypt.compare("TKIP") == 0)
                EncryptType = Ndis802_11Encryption2Enabled;
            else if (qstrEncrypt.compare("AES-WRAP") == 0)
                EncryptType = Ndis802_11Encryption3Enabled;
            else if (qstrEncrypt.compare("AES-CCMP") == 0)
                EncryptType = Ndis802_11Encryption3Enabled;
        }

        pAuthSecuDlg->Security_SetAuthModeAndEncryType(AuthenticationMode, EncryptType);
        pAuthSecuDlg->exec();

        if (pAuthSecuDlg->Security_IsClickOk() == FALSE)
            return; //Do nothing

        AuthenticationMode = pAuthSecuDlg->Security_GetAuthticationMode();
        EncryptType = pAuthSecuDlg->Security_GetEncryptType();

        if ( AuthenticationMode >= Ndis802_11AuthModeAutoSwitch)
        {
            nKeyLen = 32;
            lBufLen = (sizeof(NDIS_802_11_KEY) + nKeyLen - 1);
            // Allocate Resouce
            pKey = (PNDIS_802_11_KEY)malloc(lBufLen); // Don't use GMEM_ZEROINIT to get random key
            pKey->Length = lBufLen;
            pKey->KeyLength = nKeyLen;
            pKey->KeyIndex = 0x80000000;

            strPsk = pAuthSecuDlg->Security_GetPSKString();

            if (bHiddenSsid)
                PasswordHash((char *)strPsk.data(), m_SsidSet.Ssid, m_SsidSet.SsidLength, keyMaterial);
            else
                PasswordHash((char *)strPsk.data(), pBssid->Ssid.Ssid, pBssid->Ssid.SsidLength, keyMaterial);

            memcpy(pKey->KeyMaterial, keyMaterial, 32);

            // Set Authentication Mode
            if(pBssid->InfrastructureMode == Ndis802_11Infrastructure)
                AuthenticationMode = Ndis802_11AuthModeWPAPSK;
            else
                AuthenticationMode = Ndis802_11AuthModeWPANone;

            OidSetInformation(OID_802_11_AUTHENTICATION_MODE, m_nSocketId, m_strDeviceName, &AuthenticationMode, sizeof(AuthenticationMode));

            OidSetInformation(OID_802_11_ENCRYPTION_STATUS, m_nSocketId, m_strDeviceName, &EncryptType, sizeof(EncryptType));
            // Add Key
            OidSetInformation(RT_OID_802_11_ADD_WPA, m_nSocketId, m_strDeviceName, pKey, pKey->Length);

            // Free Resouce
            free(pKey);
        }
        else if ((AuthenticationMode == Ndis802_11AuthModeShared) || (EncryptType == Ndis802_11WEPEnabled))
        {
            // Set Authentication Mode
            OidSetInformation(OID_802_11_AUTHENTICATION_MODE, m_nSocketId, m_strDeviceName, &AuthenticationMode, sizeof(AuthenticationMode));

            // Set Encryption Status
            OidSetInformation(OID_802_11_ENCRYPTION_STATUS, m_nSocketId, m_strDeviceName, &EncryptType, sizeof(EncryptType));

            //----------------------------------------------------------//
            //Key 1
            //----------------------------------------------------------//
            strKey = pAuthSecuDlg->Security_GetWepKeyString(0);
            nKeyLen = strKey.length();
            if(nKeyLen == 0)
            {
                removeKey.Length = sizeof(NDIS_802_11_REMOVE_KEY);
                removeKey.KeyIndex = 0;
                for(i = 0; i < 6; i++)
                    removeKey.BSSID[i] = 0xff;
                OidSetInformation(OID_802_11_REMOVE_KEY, m_nSocketId, m_strDeviceName, &removeKey, removeKey.Length);
            }
            else
            {
                if(nKeyLen == 10)
                    nKeyLen = 5;
                else if(nKeyLen == 26)
                    nKeyLen = 13;

                lBufLen = sizeof(NDIS_802_11_KEY) + nKeyLen - 1;
                // Allocate Resource
                pKey = (PNDIS_802_11_KEY)malloc(lBufLen);
                pKey->Length = lBufLen;
                pKey->KeyLength = nKeyLen;
                pKey->KeyIndex = 0;
                if(pAuthSecuDlg->Security_GetDefaultKeyId() == 0)
                    pKey->KeyIndex |= 0x80000000;
                for(i = 0; i < 6; i++)
                    pKey->BSSID[i] = 0xff;

                if(strKey.length() == 5)
                    memcpy(pKey->KeyMaterial, strKey.data(), 5);
                else if(strKey.length() == 10)
                    AtoH((char *)strKey.data(), pKey->KeyMaterial, 5);
                else if(strKey.length() == 13)
                    memcpy(pKey->KeyMaterial, strKey.data(), 13);
                else if(strKey.length() == 26)
                    AtoH((char *)strKey.data(), pKey->KeyMaterial, 13);

                OidSetInformation(OID_802_11_ADD_KEY, m_nSocketId, m_strDeviceName, pKey, pKey->Length);
                free(pKey);
            }
            //----------------------------------------------------------//
            //Key 2
            //----------------------------------------------------------//
            strKey = pAuthSecuDlg->Security_GetWepKeyString(1);
            nKeyLen = strKey.length();
            if(nKeyLen == 0)
            {
                removeKey.Length = sizeof(NDIS_802_11_REMOVE_KEY);
                removeKey.KeyIndex = 1;
                for(i = 0; i < 6; i++)
                    removeKey.BSSID[i] = 0xff;
                OidSetInformation(OID_802_11_REMOVE_KEY, m_nSocketId, m_strDeviceName, &removeKey, removeKey.Length);
            }
            else
            {
                if(nKeyLen == 10)
                    nKeyLen = 5;
                else if(nKeyLen == 26)
                    nKeyLen = 13;

                lBufLen = sizeof(NDIS_802_11_KEY) + nKeyLen - 1;
                // Allocate Resource
                pKey = (PNDIS_802_11_KEY)malloc(lBufLen);
                pKey->Length = lBufLen;
                pKey->KeyLength = nKeyLen;
                pKey->KeyIndex = 1;
                if(pAuthSecuDlg->Security_GetDefaultKeyId() == 1)
                    pKey->KeyIndex |= 0x80000000;
                for(i = 0; i < 6; i++)
                    pKey->BSSID[i] = 0xff;

                if(strKey.length() == 5)
                    memcpy(pKey->KeyMaterial, strKey.data(), 5);
                else if(strKey.length() == 10)
                    AtoH((char *)strKey.data(), pKey->KeyMaterial, 5);
                else if(strKey.length() == 13)
                    memcpy(pKey->KeyMaterial, strKey.data(), 13);
                else if(strKey.length() == 26)
                    AtoH((char *)strKey.data(), pKey->KeyMaterial, 13);

                OidSetInformation(OID_802_11_ADD_KEY, m_nSocketId, m_strDeviceName, pKey, pKey->Length);
                free(pKey);
            }
            //----------------------------------------------------------//
            //Key 3
            //----------------------------------------------------------//
            strKey = pAuthSecuDlg->Security_GetWepKeyString(2);
            nKeyLen = strKey.length();
            if(nKeyLen == 0)
            {
                removeKey.Length = sizeof(NDIS_802_11_REMOVE_KEY);
                removeKey.KeyIndex = 2;
                for(i = 0; i < 6; i++)
                    removeKey.BSSID[i] = 0xff;
                OidSetInformation(OID_802_11_REMOVE_KEY, m_nSocketId, m_strDeviceName, &removeKey, removeKey.Length);
            }
            else
            {
                if(nKeyLen == 10)
                    nKeyLen = 5;
                else if(nKeyLen == 26)
                    nKeyLen = 13;

                lBufLen = sizeof(NDIS_802_11_KEY) + nKeyLen - 1;
                // Allocate Resource
                pKey = (PNDIS_802_11_KEY)malloc(lBufLen);
                pKey->Length = lBufLen;
                pKey->KeyLength = nKeyLen;
                pKey->KeyIndex = 2;
                if(pAuthSecuDlg->Security_GetDefaultKeyId() == 2)
                    pKey->KeyIndex |= 0x80000000;
                for(i = 0; i < 6; i++)
                    pKey->BSSID[i] = 0xff;

                if(strKey.length() == 5)
                    memcpy(pKey->KeyMaterial, strKey.data(), 5);
                else if(strKey.length() == 10)
                    AtoH((char *)strKey.data(), pKey->KeyMaterial, 5);
                else if(strKey.length() == 13)
                    memcpy(pKey->KeyMaterial, strKey.data(), 13);
                else if(strKey.length() == 26)
                    AtoH((char *)strKey.data(), pKey->KeyMaterial, 13);

                OidSetInformation(OID_802_11_ADD_KEY, m_nSocketId, m_strDeviceName, pKey, pKey->Length);
                free(pKey);
            }
            //----------------------------------------------------------//
            //Key 4
            //----------------------------------------------------------//
            strKey = pAuthSecuDlg->Security_GetWepKeyString(3);
            nKeyLen = strKey.length();
            if(nKeyLen == 0)
            {
                removeKey.Length = sizeof(NDIS_802_11_REMOVE_KEY);
                removeKey.KeyIndex = 3;
                for(i = 0; i < 6; i++)
                    removeKey.BSSID[i] = 0xff;
                OidSetInformation(OID_802_11_REMOVE_KEY, m_nSocketId, m_strDeviceName, &removeKey, removeKey.Length);
            }
            else
            {
                if(nKeyLen == 10)
                    nKeyLen = 5;
                else if(nKeyLen == 26)
                    nKeyLen = 13;

                lBufLen = sizeof(NDIS_802_11_KEY) + nKeyLen - 1;
                // Allocate Resource
                pKey = (PNDIS_802_11_KEY)malloc(lBufLen);
                pKey->Length = lBufLen;
                pKey->KeyLength = nKeyLen;
                pKey->KeyIndex = 3;
                if(pAuthSecuDlg->Security_GetDefaultKeyId() == 3)
                    pKey->KeyIndex |= 0x80000000;
                for(i = 0; i < 6; i++)
                    pKey->BSSID[i] = 0xff;

                if(strKey.length() == 5)
                    memcpy(pKey->KeyMaterial, strKey.data(), 5);
                else if(strKey.length() == 10)
                    AtoH((char *)strKey.data(), pKey->KeyMaterial, 5);
                else if(strKey.length() == 13)
                    memcpy(pKey->KeyMaterial, strKey.data(), 13);
                else if(strKey.length() == 26)
                    AtoH((char *)strKey.data(), pKey->KeyMaterial, 13);

                OidSetInformation(OID_802_11_ADD_KEY, m_nSocketId, m_strDeviceName, pKey, pKey->Length);
                free(pKey);
            }
        }
        else
        {
            // Set Authentication Mode
            OidSetInformation(OID_802_11_AUTHENTICATION_MODE, m_nSocketId, m_strDeviceName, &AuthenticationMode, sizeof(AuthenticationMode));

            // Set Encryption Status
            OidSetInformation(OID_802_11_ENCRYPTION_STATUS, m_nSocketId, m_strDeviceName, &EncryptType, sizeof(EncryptType));
        }
    }
    else
    {
        // Set Authentication Mode
        OidSetInformation(OID_802_11_AUTHENTICATION_MODE, m_nSocketId, m_strDeviceName, &AuthenticationMode, sizeof(AuthenticationMode));

        // Set Encryption Status
        OidSetInformation(OID_802_11_ENCRYPTION_STATUS, m_nSocketId, m_strDeviceName, &EncryptType, sizeof(EncryptType));
    }

    SiteSurvey_LineEdit_Status->setText("Connecting");


    if (!bHiddenSsid)
        memcpy(&m_SsidSet, &pBssid->Ssid, sizeof(NDIS_802_11_SSID)); // Prepare SSID for retry after retry 5 times BSSID

    if ((pBssid->InfrastructureMode == Ndis802_11IBSS) || bHiddenSsid) // Ad hoc use SSID
    {
        // Set SSID
        OidSetInformation(OID_802_11_SSID, m_nSocketId, m_strDeviceName, &m_SsidSet, sizeof(m_SsidSet));
        m_bSetSsid = TRUE;
        m_bSetBssid = FALSE;
    }
    else
    {
        memcpy(m_BssidSet, pBssid->MacAddress, sizeof(NDIS_802_11_MAC_ADDRESS));
        // Set BSSID
        OidSetInformation(OID_802_11_BSSID, m_nSocketId, m_strDeviceName, m_BssidSet, sizeof(NDIS_802_11_MAC_ADDRESS));
        m_bSetBssid = TRUE;
        m_bSetSsid = FALSE;
    }

    m_bUpdateProfilePage = TRUE;
    m_bUpdateLinkSatusPage = TRUE;
    timerId_ConnectStatus = startTimer(2000);
}

void RaConfigForm::SiteSurvey_ButtonShowHide()
{
    NDIS_802_11_AUTHENTICATION_MODE    EncrypType;

    if (G_bRadio)
        SiteSurvey_PushButton_Rescan->setEnabled( TRUE );
    else
        SiteSurvey_PushButton_Rescan->setEnabled( FALSE );

    EncrypType = SiteSurvey_GetEncryStatus();
    if ((!G_bRadio) || (SiteSurvey_ListView->childCount() <= 0) || 
        (EncrypType == Ndis802_11AuthModeAutoSwitch) ||
        (EncrypType == Ndis802_11AuthModeWPA)  || 
        (EncrypType == Ndis802_11AuthModeWPANone) ||
        (EncrypType == Ndis802_11AuthModeMax))
    {
        SiteSurvey_PushButton_Connect->setEnabled( FALSE );
        SiteSurvey_PushButton_AddProfile->setEnabled( FALSE );
    }
    else
    {
        if(G_bUserAdmin)
        {
            SiteSurvey_PushButton_Connect->setEnabled( TRUE );
            SiteSurvey_PushButton_AddProfile->setEnabled( TRUE );
        }
        else
        {
            SiteSurvey_PushButton_Connect->setEnabled( FALSE );
            SiteSurvey_PushButton_AddProfile->setEnabled( FALSE );
        }
    }

}

NDIS_802_11_AUTHENTICATION_MODE RaConfigForm::SiteSurvey_GetEncryStatus()
{
    QListViewItem                       *selectedItem;
    QString                             qstrAuthenMode;
    QString                             qstrEncrypType;
    NDIS_802_11_AUTHENTICATION_MODE     status = Ndis802_11AuthModeWPANone;

	selectedItem = SiteSurvey_ListView->selectedItem();
	if (!selectedItem)
        return (status);

    qstrAuthenMode = selectedItem->text(5);
    qstrEncrypType = selectedItem->text(4);
    if (qstrAuthenMode.compare("Unknown") == 0)
    {
        if (qstrEncrypType.compare("WEP") == 0)
            status = Ndis802_11AuthModeOpen;
        else if (qstrEncrypType.compare("Not Use") == 0)
            status = Ndis802_11AuthModeOpen;
    }
    else if (qstrAuthenMode.compare("Shared Key") == 0)
        status = Ndis802_11AuthModeShared;
    else if (qstrAuthenMode.compare("WPA") == 0)
        status = Ndis802_11AuthModeWPA;
    else if (qstrAuthenMode.compare("WPAPSK") == 0)
        status = Ndis802_11AuthModeWPAPSK;
    else if (qstrAuthenMode.compare("WPA-None") == 0)
        status = Ndis802_11AuthModeWPANone;
    else 
        status = Ndis802_11AuthModeMax;

    return (status);
}

void RaConfigForm::SiteSurvey_OnAddToProfile()
{
    AddProfileDlg                           *pAddProfileDlg;
    QListViewItem                           *selectedItem;
    PNDIS_WLAN_BSSID_EX                     pBssid;
    NDIS_802_11_MAC_ADDRESS                 CurBssid;
    NDIS_802_11_AUTHENTICATION_MODE         AuthenticationMode = Ndis802_11AuthModeOpen;
    NDIS_802_11_ENCRYPTION_STATUS           EncryptType = Ndis802_11WEPDisabled;
    QString                                 qstrSsid;
    QString                                 qstrBssid;
    QString                                 qstrAuthen;
    QString                                 qstrEncrypt;
    char                                    strSSID[NDIS_802_11_LENGTH_SSID + 1];
    ULONG                                   index;
    int                                     nChannel;
    int                                     i = 0;
    bool                                    bfound = FALSE;
    bool                                    bHiddenSsid = FALSE;

    if (!G_bUserAdmin)
        return;

    selectedItem = SiteSurvey_ListView->selectedItem();
    if (!selectedItem)
    {
        QMessageBox::warning(this, "Warning", "No selected Item!");
        return;
    }

    if (!m_pBssidList)
        return;

    qstrBssid = selectedItem->text(1);
    while ( ( i = qstrBssid.find( '-', i ) ) != -1 )
        qstrBssid.remove( i ,1 );

    AtoH((char *)qstrBssid.data(), CurBssid, 6);

    pBssid = (PNDIS_WLAN_BSSID_EX) m_pBssidList->Bssid;
    for (index = 0; index < m_pBssidList->NumberOfItems; index++)
    {
        if (memcmp(pBssid->MacAddress, CurBssid, 6) == 0)
        {
            bfound = TRUE;
            break;
        }
        pBssid = (PNDIS_WLAN_BSSID_EX)((char *)pBssid + pBssid->Length);
    }
    
    if (!bfound)
        return;

    memset(strSSID, 0x00, NDIS_802_11_LENGTH_SSID + 1);
    memcpy(strSSID, pBssid->Ssid.Ssid, pBssid->Ssid.SsidLength);

    nChannel = -1;

    for (i = 0; i < G_nChanFreqCount; i++)
    {
        if (pBssid->Configuration.DSConfig == ChannelFreqTable[i].lFreq)
        {
            nChannel = ChannelFreqTable[i].lChannel;
            break;
        }
    }

    if(nChannel == -1)
        return;

    qstrAuthen = selectedItem->text(5);
    qstrEncrypt = selectedItem->text(4);

    if (qstrAuthen.compare("Unknown") == 0)
    {
        if (qstrEncrypt.compare("WEP") == 0)
        {
            EncryptType = Ndis802_11WEPEnabled;
            AuthenticationMode = Ndis802_11AuthModeOpen;
        }
    }
    else if (qstrAuthen.compare("WPAPSK") == 0)
    {
        AuthenticationMode = Ndis802_11AuthModeWPAPSK;
        if (qstrEncrypt.compare("TKIP") == 0)
            EncryptType = Ndis802_11Encryption2Enabled;
        else if (qstrEncrypt.compare("AES-WRAP") == 0)
            EncryptType = Ndis802_11Encryption3Enabled;
        else if (qstrEncrypt.compare("AES-CCMP") == 0)
            EncryptType = Ndis802_11Encryption3Enabled;
    }
    else if (qstrAuthen.compare("WPA-None") == 0)
    {
        AuthenticationMode = Ndis802_11AuthModeWPANone;
        if (qstrEncrypt.compare("TKIP") == 0)
            EncryptType = Ndis802_11Encryption2Enabled;
        else if (qstrEncrypt.compare("AES-WRAP") == 0)
            EncryptType = Ndis802_11Encryption3Enabled;
        else if (qstrEncrypt.compare("AES-CCMP") == 0)
            EncryptType = Ndis802_11Encryption3Enabled;
    }
    else if (qstrAuthen.compare("WPA") == 0)
    {
        AuthenticationMode = Ndis802_11AuthModeWPA;
        if (qstrEncrypt.compare("TKIP") == 0)
            EncryptType = Ndis802_11Encryption2Enabled;
        else if (qstrEncrypt.compare("AES-WRAP") == 0)
            EncryptType = Ndis802_11Encryption3Enabled;
        else if (qstrEncrypt.compare("AES-CCMP") == 0)
            EncryptType = Ndis802_11Encryption3Enabled;
    }

    if (pBssid->Ssid.SsidLength == 0)
    {
        HiddenSsidDlg *pHiddendlg = new HiddenSsidDlg(this, "HiddenSsid", TRUE);

        pHiddendlg->exec();
        if (pHiddendlg->IsClickOk())
        {
            qstrSsid = pHiddendlg->GetSsidString();
            bHiddenSsid = TRUE;
        }
        else
            return;
    }

    pAddProfileDlg = new AddProfileDlg(m_nSocketId, m_strDeviceName, this, "AddProfile", PROFILE_ADD, Profile_ListView, &m_pProfileSetting, &CurBssid, TRUE);
    if (bHiddenSsid)
        pAddProfileDlg->Config_SetCurrentSSID(qstrSsid);
    pAddProfileDlg->Security_SetAuthModeAndEncryType(pBssid->InfrastructureMode, AuthenticationMode, EncryptType);
    pAddProfileDlg->exec();

    if (pAddProfileDlg->IsOk())
    {
        Profile_WriteProfileToFile();
        
        if (Profile_ListView->childCount() == 0 )
        {
            Profile_PushButton_Delete->setEnabled(FALSE);
            Profile_PushButton_Edit->setEnabled(FALSE);
            Profile_PushButton_Activate->setEnabled(FALSE);
        }
        else
        {
            Profile_PushButton_Delete->setEnabled(TRUE);
            Profile_PushButton_Edit->setEnabled(TRUE);
            Profile_PushButton_Activate->setEnabled(TRUE);
        }

        TabWidgetRaConfig->setCurrentPage(0);
    }
    delete pAddProfileDlg;
}

void RaConfigForm::LinkStatus_OnActive()
{
    RT_802_11_LINK_STATUS       LinkStatus;

    if (OidQueryInformation(RT_OID_802_11_LINK_STATUS, m_nSocketId, m_strDeviceName, &LinkStatus, sizeof(&LinkStatus)) >= 0)
    {
        m_lTxCount = LinkStatus.TxByteCount;
        m_lRxCount = LinkStatus.RxByteCount;
    }

    timerId_LinkStatus = startTimer(2000);
}

void RaConfigForm::LinkStatus_UpdateStatus()
{
    NDIS_MEDIA_STATE                    ConnectStatus = NdisMediaStateDisconnected;
    NDIS_802_11_SSID                    SSID;
    NDIS_802_11_MAC_ADDRESS             Bssid;
    NDIS_802_11_CONFIGURATION           Configuration;
    RT_802_11_LINK_STATUS               LinkStatus;
    NDIS_802_11_RSSI                    RSSI;
    QString                             qstrStatus;
    QString                             qstrChannel;
    QString                             qstrTxRate;
    QString                             qstrTxThrougput;
    QString                             qstrRxThrougput;
    QString                             qstrLinkQuality;
    QString                             qstrSignalQuality;
    char                                strSSID[NDIS_802_11_LENGTH_SSID + 1];    
    unsigned int                        nSigQua;
    int                                 nChannel = -1;
    int                                 i;

    OidQueryInformation(OID_GEN_MEDIA_CONNECT_STATUS, m_nSocketId, m_strDeviceName, &ConnectStatus, sizeof(ConnectStatus));

    if (ConnectStatus == NdisMediaStateConnected)
    {
        memset(&SSID, 0x00, sizeof(SSID));        
        OidQueryInformation(OID_802_11_SSID, m_nSocketId, m_strDeviceName, &SSID, sizeof(SSID));

        memset(&Bssid, 0x00, sizeof(Bssid));        
        OidQueryInformation(OID_802_11_BSSID, m_nSocketId, m_strDeviceName, &Bssid, sizeof(Bssid));

        memset(strSSID, 0x00, NDIS_802_11_LENGTH_SSID + 1);
        memcpy(strSSID, SSID.Ssid, SSID.SsidLength);

        qstrStatus.sprintf("%s <--> %02X-%02X-%02X-%02X-%02X-%02X", strSSID, Bssid[0], Bssid[1], Bssid[2], Bssid[3], Bssid[4], Bssid[5] );
        LinkStatus_TextLabel_Status->setText(qstrStatus);
    }
    else
    {
        if (G_bRadio)
            qstrStatus.sprintf("Disconnected");
        else
            qstrStatus.sprintf("Radio Status <--> OFF");

        LinkStatus_TextLabel_Status->setText(qstrStatus);
        LinkStatus_TextLabel_Channel->setText("");
        LinkStatus_TextLabel_TxRate->setText("");
        LinkStatus_TextLabel_TxThrougput->setText("");
        LinkStatus_TextLabel_RxThroughput->setText("");
        LinkStatus_TextLabel_Link->setText("");
        LinkStatus_TextLabel_Signal->setText("");
        LinkStatus_ProgressBar_Link->setProgress(0);
        LinkStatus_ProgressBar_Signal->setProgress(0);

        return;
    }

    // Current Channel
    memset(&Configuration, 0x00, sizeof(Configuration));    
    OidQueryInformation(OID_802_11_CONFIGURATION, m_nSocketId, m_strDeviceName, &Configuration, sizeof(Configuration));

    for (i = 0; i < G_nChanFreqCount; i++)
    {
        if (Configuration.DSConfig == ChannelFreqTable[i].lFreq)
        {
            nChannel = ChannelFreqTable[i].lChannel;
            break;
        }
    }

    if (nChannel != -1)
    {
        qstrChannel.sprintf("%u <--> %ld KHz", nChannel, Configuration.DSConfig);
        LinkStatus_TextLabel_Channel->setText(qstrChannel);
    }

    memset(&LinkStatus, 0x00, sizeof(LinkStatus));    
    if (OidQueryInformation(RT_OID_802_11_LINK_STATUS, m_nSocketId, m_strDeviceName, &LinkStatus, sizeof(LinkStatus)) >= 0)
    {
        // Current Tx Rate LinkStatus.CurrTxRate / 2(secs)
        if ((LinkStatus.CurrTxRate % 2) == 0)
            qstrTxRate.sprintf("%ld Mbps", LinkStatus.CurrTxRate / 2);
        else
            qstrTxRate.sprintf("%.1f Mbps", double(LinkStatus.CurrTxRate) / 2 );

        LinkStatus_TextLabel_TxRate->setText(qstrTxRate);
        // Tx Throughput (KBits/sec) (LinkStatus.TxByteCount - m_lTxCount) * 8(bits) /1000 / 2(secs)
        qstrTxThrougput.sprintf("%.1f", (double)(LinkStatus.TxByteCount - m_lTxCount) / 250);
        LinkStatus_TextLabel_TxThrougput->setText(qstrTxThrougput);
        m_lTxCount = LinkStatus.TxByteCount;

        // Rx Throughput (KBits/sec) (LinkStatus.RxByteCount - m_lRxCount) * 8(bits) /1000 / 2(secs)
        qstrRxThrougput.sprintf("%.1f", (double)(LinkStatus.RxByteCount - m_lRxCount) / 250);
        LinkStatus_TextLabel_RxThroughput->setText(qstrRxThrougput);
        m_lRxCount = LinkStatus.RxByteCount;

        // Link Quality
        LinkStatus.ChannelQuality = (ULONG)(LinkStatus.ChannelQuality * 1.2 + 10);
        if (LinkStatus.ChannelQuality > 100)
            LinkStatus.ChannelQuality = 100;

        if (m_lChannelQuality != 0)
            LinkStatus.ChannelQuality = (ULONG)((m_lChannelQuality + LinkStatus.ChannelQuality) / 2.0 + 0.5);

        m_lChannelQuality = LinkStatus.ChannelQuality;

        if (LinkStatus.ChannelQuality > 70)
            qstrLinkQuality.sprintf("Good %ld%%", LinkStatus.ChannelQuality);
        else if(LinkStatus.ChannelQuality > 40)
            qstrLinkQuality.sprintf("Normal %ld%%", LinkStatus.ChannelQuality);
        else
            qstrLinkQuality.sprintf("Weak %ld%%", LinkStatus.ChannelQuality);

        LinkStatus_TextLabel_Link->setText(qstrLinkQuality);
        LinkStatus_ProgressBar_Link->setProgress(LinkStatus.ChannelQuality);
    }

    
    // Signal Strength
    memset(&RSSI, 0x00, sizeof(RSSI));
    if (OidQueryInformation(OID_802_11_RSSI, m_nSocketId, m_strDeviceName, &RSSI, sizeof(RSSI)) >= 0)
    {
        // Use convert formula to getSignal Quality
        nSigQua = ConvertRssiToSignalQuality(RSSI);

        if (m_nSigQua !=0)
            nSigQua = (unsigned int)((m_nSigQua + nSigQua) / 2.0 + 0.5);

        m_nSigQua = nSigQua;
            
        if (nSigQua > 70)
        {
            if (LinkStatus_CheckBox_dbm->isChecked())
                qstrSignalQuality.sprintf("Good %ld dBm", RSSI);
            else
                qstrSignalQuality.sprintf("Good %d%%", nSigQua);
        }
        else if (nSigQua > 40)
        {
            if (LinkStatus_CheckBox_dbm->isChecked())
                qstrSignalQuality.sprintf("Normal %ld dBm", RSSI);
            else
                qstrSignalQuality.sprintf("Normal %d%%", nSigQua);
        }
        else
        {
            if (LinkStatus_CheckBox_dbm->isChecked())
                qstrSignalQuality.sprintf("Weak %ld dBm", RSSI);
            else
                qstrSignalQuality.sprintf("Weak %d%%", nSigQua);
        }

        LinkStatus_TextLabel_Signal->setText(qstrSignalQuality);
        LinkStatus_ProgressBar_Signal->setProgress(nSigQua);
    }
}

void RaConfigForm::Statistics_OnActive()
{
    timerId_Statistic = startTimer(2000);    
}

void RaConfigForm::Statistics_OnTimer()
{
    NDIS_802_11_STATISTICS              Statistics;
    ULONG                               lRcvOk = 0;
    ULONG                               lRcvNoBuf = 0;
    char                                tmp[255];

    // Transmit Section
    memset(&Statistics, 0x00, sizeof(Statistics));    
    if (OidQueryInformation(OID_802_11_STATISTICS, m_nSocketId, m_strDeviceName, &Statistics, sizeof(Statistics)) >= 0)
    {
        // Frames Transmitted Successfully        
        sprintf(tmp, "%8lld", Statistics.TransmittedFragmentCount);
        Statistics_TextLabel_TxSuccess->setText(tmp);

        // Frames Transmitted Successfully After Retry(s)
        sprintf(tmp, "%8lld", Statistics.RetryCount);
        Statistics_TextLabel_TxAfterRetry->setText(tmp);

        // Frames Transmitted Successfully  Without Retry(s) 
        sprintf(tmp, "%8lld", Statistics.TransmittedFragmentCount - Statistics.RetryCount);
        Statistics_TextLabel_TxWithoutRetry->setText(tmp);

        // Frames Fail To Receive ACK After All Retries
        sprintf(tmp, "%8lld", Statistics.FailedCount);
        Statistics_TextLabel_TxFailACK->setText(tmp);

        // RTS Frames Successfully Receive CTS
        sprintf(tmp, "%8lld", Statistics.RTSSuccessCount);
        Statistics_TextLabel_RTSSuccess->setText(tmp);

        // RTS Frames Fail To Receive CTS
        sprintf(tmp, "%8lld", Statistics.RTSFailureCount);
        Statistics_TextLabel_RTSFail->setText(tmp);

        // Frames Received With CRC Error
        sprintf(tmp, "%8lld", Statistics.FCSErrorCount);
        Statistics_TextLabel_RxCRC->setText(tmp);

        // Duplicate Frames Received
        sprintf(tmp, "%8lld", Statistics.FrameDuplicateCount);
        Statistics_TextLabel_Duplicate->setText(tmp);
    }

    // Frames Received Successfully
    if (OidQueryInformation(OID_GEN_RCV_OK, m_nSocketId, m_strDeviceName, &lRcvOk, sizeof(lRcvOk)) >= 0)
    {          
        sprintf(tmp, "%ld", lRcvOk);
        Statistics_TextLabel_RxSuccess->setText(tmp);
    }
    
    // Frames Dropped Due To Out-of-Resource
    if (OidQueryInformation(OID_GEN_RCV_NO_BUFFER, m_nSocketId, m_strDeviceName, &lRcvNoBuf, sizeof(lRcvNoBuf)) >= 0)
    {
        sprintf(tmp, "%ld", lRcvNoBuf);
        Statistics_TextLabel_RxDrop->setText(tmp);
    }        
}

void RaConfigForm::Statistics_OnResetCounters()
{
    Statistics_TextLabel_TxSuccess->setText(0);
    Statistics_TextLabel_TxAfterRetry->setText(0);
    Statistics_TextLabel_TxWithoutRetry->setText(0);
    Statistics_TextLabel_TxFailACK->setText(0);
    Statistics_TextLabel_RTSSuccess->setText(0);
    Statistics_TextLabel_RTSFail->setText(0);
    Statistics_TextLabel_RxCRC->setText(0);
    Statistics_TextLabel_Duplicate->setText(0);
    Statistics_TextLabel_RxSuccess->setText(0);
    Statistics_TextLabel_RxDrop->setText(0);

    OidSetInformation(RT_OID_802_11_RESET_COUNTERS, m_nSocketId, m_strDeviceName, 0, 0);
}

void RaConfigForm::Advance_OnActive()
{
    if(G_bSupportAMode)
    {
        Advance_ComboBox_Mode->insertItem("802.11 A only");
        Advance_ComboBox_Mode->insertItem("802.11 A/B/G mixed mode");
    }

    if(G_bRadio)
    {
        Advance_PushButton_Radio->setText("RADIO OFF");
        Advance_TextLabel_Radio->setPixmap( uic_load_pixmap_RaConfigForm( "radioon.png" ) );
    }
    else
    {
        Advance_PushButton_Radio->setText("RADIO ON");
        Advance_TextLabel_Radio->setPixmap( uic_load_pixmap_RaConfigForm( "radiooff.png" ) );
    }

    Advance_ReadConfigFromRegistry();
    Advance_OnSelchangeWirelessMode( Advance_ComboBox_Mode->currentItem());
}

void RaConfigForm::Advance_ReadConfigFromRegistry()
{
    char            strtmp[255];
    unsigned int    nWirelessMode;

    if (getkeystring("Default", "WirelessMode",  strtmp, 255, RT2500_SYSTEM_PATH, RT2500_SYSTEM_DATA) == TRUE)
    {
        nWirelessMode = atoi(strtmp);

        if (G_bSupportAMode)
        {
            if ( nWirelessMode > PHY_11ABG_MIXED )
                m_WirelessMode = PHY_11ABG_MIXED;                
            else
                m_WirelessMode = (RT_802_11_PHY_MODE) nWirelessMode;
        }
        else
        {
            if (nWirelessMode >= PHY_11A )
                m_WirelessMode = PHY_11BG_MIXED;
            else
                m_WirelessMode = (RT_802_11_PHY_MODE) nWirelessMode;

        }
        Advance_ComboBox_Mode->setCurrentItem( (int)m_WirelessMode);
    }
    
    if (getkeystring("Default", "AdhocOfdm",  strtmp, 255, RT2500_SYSTEM_PATH, RT2500_SYSTEM_DATA) == TRUE)
    {
        if (atoi(strtmp) != 0)
            m_bAdhocOfdm = TRUE;
        else
            m_bAdhocOfdm = FALSE;

        Advance_CheckBox_AdhocOfdm->setChecked(m_bAdhocOfdm);
    }

    if (getkeystring("Default", "TXBurst",  strtmp, 255, RT2500_SYSTEM_PATH, RT2500_SYSTEM_DATA) == TRUE)
    {
        if (atoi(strtmp) != 0)
            m_bTXBurst = TRUE;
        else
            m_bTXBurst = FALSE;

        Advance_CheckBox_TxBurst->setChecked(m_bTXBurst);
    }

    if (getkeystring("Default", "TurboRate",  strtmp, 255, RT2500_SYSTEM_PATH, RT2500_SYSTEM_DATA) == TRUE)
    {
        if (atoi(strtmp) != 0)
            m_bTurboRate = TRUE;
        else
            m_bTurboRate = FALSE;

        Advance_CheckBox_TurboRate->setChecked(m_bTurboRate);
    }

    if (getkeystring("Default", "ShortSlot",  strtmp, 255, RT2500_SYSTEM_PATH, RT2500_SYSTEM_DATA) == TRUE)
    {
        if (atoi(strtmp) != 0)
            m_bShortSlot = TRUE;
        else
            m_bShortSlot = FALSE;

        Advance_CheckBox_ShortSlot->setChecked(m_bShortSlot);
    }
    
    if (getkeystring("Default", "BGProtection",  strtmp, 255, RT2500_SYSTEM_PATH, RT2500_SYSTEM_DATA) == TRUE)
    {
        m_nBGProtection = atoi(strtmp);

        if ((m_nBGProtection < 0) || (m_nBGProtection >= 3))
            m_nBGProtection = 0;

        Advance_ComboBox_BGProtection->setCurrentItem(m_nBGProtection);
    }

    if (getkeystring("Default", "TxRate",  strtmp, 255, RT2500_SYSTEM_PATH, RT2500_SYSTEM_DATA) == TRUE)
    {
        m_nTXRate = atoi(strtmp);

        Advance_ComboBox_TxRate->setCurrentItem(m_nTXRate);
    }

}

void RaConfigForm::Advance_OnSelchangeWirelessMode(int index)
{
    Advance_ComboBox_TxRate->clear();

    if (index == 0)
        m_WirelessMode = PHY_11BG_MIXED;
    else
        m_WirelessMode = PHY_11B;

    switch(m_WirelessMode)
    {
        case PHY_11B: // B only
            Advance_ComboBox_TxRate->insertItem("Auto");
            Advance_ComboBox_TxRate->insertItem("1 Mbps");
            Advance_ComboBox_TxRate->insertItem("2 Mbps");
            Advance_ComboBox_TxRate->insertItem("5.5 Mbps");
            Advance_ComboBox_TxRate->insertItem("11 Mbps");
            Advance_ComboBox_BGProtection->setEnabled(FALSE);

            m_nBGProtection = 0;
            if(m_nTXRate > 4)
                m_nTXRate = 0;
            break;
        case PHY_11A: // A Only
            Advance_ComboBox_TxRate->insertItem("Auto");
            Advance_ComboBox_TxRate->insertItem("6 Mbps");
            Advance_ComboBox_TxRate->insertItem("9 Mbps");
            Advance_ComboBox_TxRate->insertItem("12 Mbps");
            Advance_ComboBox_TxRate->insertItem("18 Mbps");
            Advance_ComboBox_TxRate->insertItem("24 Mbps");
            Advance_ComboBox_TxRate->insertItem("36 Mbps");
            Advance_ComboBox_TxRate->insertItem("48 Mbps");
            Advance_ComboBox_TxRate->insertItem("54 Mbps");
            Advance_ComboBox_BGProtection->setEnabled(FALSE);

            m_nBGProtection = 0;
            if(m_nTXRate > 8)
                m_nTXRate = 0;
            break;
        case PHY_11BG_MIXED: // B/G Mixed
        case PHY_11ABG_MIXED: // A/B/G Mixed
        default:
            Advance_ComboBox_TxRate->insertItem("Auto");
            Advance_ComboBox_TxRate->insertItem("1 Mbps");
            Advance_ComboBox_TxRate->insertItem("2 Mbps");
            Advance_ComboBox_TxRate->insertItem("5.5 Mbps");
            Advance_ComboBox_TxRate->insertItem("11 Mbps");
            Advance_ComboBox_TxRate->insertItem("6 Mbps");
            Advance_ComboBox_TxRate->insertItem("9 Mbps");
            Advance_ComboBox_TxRate->insertItem("12 Mbps");
            Advance_ComboBox_TxRate->insertItem("18 Mbps");
            Advance_ComboBox_TxRate->insertItem("24 Mbps");
            Advance_ComboBox_TxRate->insertItem("36 Mbps");
            Advance_ComboBox_TxRate->insertItem("48 Mbps");
            Advance_ComboBox_TxRate->insertItem("54 Mbps");
//          Advance_ComboBox_TxRate->insertItem("72 Mbps");
//          Advance_ComboBox_TxRate->insertItem("100 Mbps");

            if (G_bUserAdmin)
                Advance_ComboBox_BGProtection->setEnabled(TRUE);

            if(m_nTXRate > 12)
                m_nTXRate = 0;
            break;
    }

    Advance_ComboBox_TxRate->setCurrentItem(m_nTXRate);
}

void RaConfigForm::Advance_OnRadio()
{
    char            strtmp[255];

    G_bRadio = !G_bRadio;

    if (OidSetInformation(RT_OID_802_11_RADIO, m_nSocketId, m_strDeviceName, &G_bRadio, sizeof(G_bRadio)) >= 0)
    { //Set success
        if (G_bRadio)
        {
            Advance_PushButton_Radio->setText("RADIO OFF");
            Advance_TextLabel_Radio->setPixmap( uic_load_pixmap_RaConfigForm( "radioon.png" ) );
        }
        else
        {
            Advance_PushButton_Radio->setText("RADIO ON");
            Advance_TextLabel_Radio->setPixmap( uic_load_pixmap_RaConfigForm( "radiooff.png" ) );
        }

        if (G_bUserAdmin)
        {
            sprintf(strtmp, "%d", G_bRadio);
            writekeystring("Default", "Radio", strtmp, RT2500_SYSTEM_PATH, RT2500_SYSTEM_DATA);
        }
    }
    else
    { //Set failed
        G_bRadio = !G_bRadio;
    }

    OidSetInformation(OID_802_11_BSSID_LIST_SCAN, m_nSocketId, m_strDeviceName, 0, 0);
    LinkStatus_UpdateStatus();
    Profile_UpdateProfileStatus();
    SiteSurvey_ProbeConnectStatus();

}

void RaConfigForm::Advance_OnApply()
{
    RT_802_11_PHY_MODE          enumWirelessMode;
    RT_802_11_STA_CONFIG        configStation;
    RT_802_11_STA_CONFIG        configOldStation;
    NDIS_802_11_RATES           aryRates;
    char                        strtmp[255];

    m_nTXRate = Advance_ComboBox_TxRate->currentItem();

    if (!G_bSupportAMode && (m_WirelessMode >= PHY_11A))
        m_WirelessMode = PHY_11BG_MIXED;

    G_enumWirelessMode = (RT_802_11_PHY_MODE)m_WirelessMode;
    if ((m_WirelessMode == PHY_11B) || (m_WirelessMode == PHY_11A))
        m_nBGProtection = 0;
    if (((m_WirelessMode == PHY_11B) && (m_nTXRate > 4)) || ((m_WirelessMode == PHY_11A) && (m_nTXRate > 8)))
        m_nTXRate = 0;

    m_bAdhocOfdm = Advance_CheckBox_AdhocOfdm->isChecked();
    m_bTurboRate = Advance_CheckBox_TurboRate->isChecked();
    m_bTXBurst = Advance_CheckBox_TxBurst->isChecked();
    m_bShortSlot = Advance_CheckBox_ShortSlot->isChecked();
    switch (Advance_ComboBox_BGProtection->currentItem())
    {
    case 1://1-always ON
        m_nBGProtection = 1;
        break;
    case 2://2-always OFF
        m_nBGProtection = 2;
        break;
    case 0:// 0-AUTO
    default:
        m_nBGProtection = 0;
        break;
    }

    if (G_bUserAdmin)
    {
        // Set Wireless Mode value
        sprintf(strtmp, "%d", m_WirelessMode);
        writekeystring("Default", "WirelessMode", strtmp, RT2500_SYSTEM_PATH, RT2500_SYSTEM_DATA);

        //Set AdhocOfdm
        sprintf(strtmp, "%d", m_bAdhocOfdm);
        writekeystring("Default", "AdhocOfdm", strtmp, RT2500_SYSTEM_PATH, RT2500_SYSTEM_DATA);

        // Set TXBurst value
        sprintf(strtmp, "%d", m_bTXBurst);
        writekeystring("Default", "TXBurst", strtmp, RT2500_SYSTEM_PATH, RT2500_SYSTEM_DATA);
        
        // Set TurboRate value
        sprintf(strtmp, "%d", m_bTurboRate);
        writekeystring("Default", "TurboRate", strtmp, RT2500_SYSTEM_PATH, RT2500_SYSTEM_DATA);

        // Set BGProtection value
        sprintf(strtmp, "%d", m_nBGProtection);
        writekeystring("Default", "BGProtection", strtmp, RT2500_SYSTEM_PATH, RT2500_SYSTEM_DATA);

        // Set ShortSlot value
        sprintf(strtmp, "%d", m_bShortSlot);
        writekeystring("Default", "ShortSlot", strtmp, RT2500_SYSTEM_PATH, RT2500_SYSTEM_DATA);

        // Set TXRate value
        sprintf(strtmp, "%d", m_nTXRate);
        writekeystring("Default", "TxRate", strtmp, RT2500_SYSTEM_PATH, RT2500_SYSTEM_DATA);
    }
 
    // SetOidInformation
    OidQueryInformation(RT_OID_802_11_PHY_MODE, m_nSocketId, m_strDeviceName, &enumWirelessMode, sizeof(enumWirelessMode));
    if(enumWirelessMode != G_enumWirelessMode)
        OidSetInformation(RT_OID_802_11_PHY_MODE, m_nSocketId, m_strDeviceName, &G_enumWirelessMode, sizeof(G_enumWirelessMode));

    OidQueryInformation(RT_OID_802_11_STA_CONFIG, m_nSocketId, m_strDeviceName, &configOldStation, sizeof(configOldStation));

    configStation.EnableTurboRate = m_bTurboRate;
    configStation.EnableTxBurst = m_bTXBurst;
    configStation.UseBGProtection = m_nBGProtection;
    configStation.UseShortSlotTime = m_bShortSlot;
    configStation.UseOfdmRatesIn11gAdhoc = m_bAdhocOfdm;

    if(memcmp(&configOldStation, &configStation, sizeof(RT_802_11_STA_CONFIG)) != 0)        
        OidSetInformation(RT_OID_802_11_STA_CONFIG, m_nSocketId, m_strDeviceName, &configStation, sizeof(configStation));

    memset(aryRates, 0x00, sizeof(NDIS_802_11_RATES));
    if (m_WirelessMode == PHY_11A)
    {
        switch (m_nTXRate)
        {
        case 0:
            aryRates[0] = 0x6c; // 54Mbps
            aryRates[1] = 0x60; // 48Mbps
            aryRates[2] = 0x48; // 36Mbps
            aryRates[3] = 0x30; // 24Mbps
            aryRates[4] = 0x24; // 18M
            aryRates[5] = 0x18; // 12M
            aryRates[6] = 0x12; // 9M
            aryRates[7] = 0x0c; // 6M
            break;
        case 1:
            aryRates[0] = 0x0c; // 6M
            break;
        case 2:
            aryRates[0] = 0x12; // 9M
            break;
        case 3:
            aryRates[0] = 0x18; // 12M
            break;
        case 4:
            aryRates[0] = 0x24; // 18M
            break;
        case 5:
            aryRates[0] = 0x30; // 24M
            break;
        case 6:
            aryRates[0] = 0x48; // 36M
            break;
        case 7:
            aryRates[0] = 0x60; // 48M
            break;
        case 8:
            aryRates[0] = 0x6c; // 54M
            break;
        }
    }
    else if ((m_WirelessMode == PHY_11BG_MIXED) || (m_WirelessMode == PHY_11B) ||
             (m_WirelessMode == PHY_11ABG_MIXED))
    {
        switch(m_nTXRate)
        {
        case 0:
            switch(m_WirelessMode)
            {
            case PHY_11BG_MIXED: // B/G Mixed
            case PHY_11ABG_MIXED: // A/B/G Mixed
                aryRates[0] = 0x6c; // 54Mbps
                aryRates[1] = 0x60; // 48Mbps
                aryRates[2] = 0x48; // 36Mbps
                aryRates[3] = 0x30; // 24Mbps
                aryRates[4] = 0x16; // 11Mbps
                aryRates[5] = 0x0b; // 5.5Mbps
                aryRates[6] = 0x04; // 2Mbps
                aryRates[7] = 0x02; // 1Mbps
                break;
            case PHY_11B: // B Only
                aryRates[0] = 0x16; // 11Mbps
                aryRates[1] = 0x0b; // 5.5Mbps
                aryRates[2] = 0x04; // 2Mbps
                aryRates[3] = 0x02; // 1Mbps
                break;
            case PHY_11A:
                break;   //Not be call, for avoid warning.
            }
            break;
        case 1:
            aryRates[0] = 0x02; // 1M
            break;
        case 2:
            aryRates[0] = 0x04; // 2M
            break;
        case 3:
            aryRates[0] = 0x0b; // 5.5M
            break;
        case 4:
            aryRates[0] = 0x16; // 11M
            break;
        case 5:
            aryRates[0] = 0x0c; // 6M
            break;
        case 6:
            aryRates[0] = 0x12; // 9M
            break;
        case 7:
            aryRates[0] = 0x18; // 12M
            break;
        case 8:
            aryRates[0] = 0x24; // 18M
            break;
        case 9:
            aryRates[0] = 0x30; // 24M
            break;
        case 10:
            aryRates[0] = 0x48; // 36M
            break;
        case 11:
            aryRates[0] = 0x60; // 48M
            break;
        case 12:
            aryRates[0] = 0x6c; // 54M
            break;
        }
    }
    OidSetInformation(OID_802_11_DESIRED_RATES, m_nSocketId, m_strDeviceName, &aryRates, sizeof(NDIS_802_11_RATES));
}

void RaConfigForm::About_OnActive()
{
    NDIS_802_11_MAC_ADDRESS         CurrentAddress;
    RT_VERSION_INFO                 DriverVersionInfo;
    char                            tmp[40];

    
    if( OidQueryInformation(OID_802_3_CURRENT_ADDRESS, m_nSocketId, m_strDeviceName, &CurrentAddress, sizeof(CurrentAddress)) >= 0)
    {
        sprintf(tmp, "%02X-%02X-%02X-%02X-%02X-%02X", CurrentAddress[0], CurrentAddress[1],
            CurrentAddress[2], CurrentAddress[3], CurrentAddress[4], CurrentAddress[5]);
    }
    else
    {
        sprintf(tmp, "");
    }
        About_TextLabel_PhyAddress->setText( (const char *)tmp );

    if (OidQueryInformation(RT_OID_VERSION_INFO, m_nSocketId, m_strDeviceName, &DriverVersionInfo, sizeof(DriverVersionInfo)) >= 0)
    {
        sprintf(tmp, "%d.%d.%d.%d", DriverVersionInfo.DriverVersionW, DriverVersionInfo.DriverVersionX, DriverVersionInfo.DriverVersionY, DriverVersionInfo.DriverVersionZ);
        About_TextLabel_NICVersion->setText(tmp);
        sprintf(tmp, "%04d-%02d-%02d", DriverVersionInfo.DriverBuildYear, DriverVersionInfo.DriverBuildMonth, DriverVersionInfo.DriverBuildDay);
        About_TextLabel_NICDate->setText(tmp);
    }
}

void RaConfigForm::SiteSurvey_OnSelectChange()
{
    SiteSurvey_ButtonShowHide();
}

