/*------------------------------------------------------------------------------*
 * File Name: ExtractWksDataDlg													*
 * Creation : Sim 04-13-2009													*
 * Purpose: OriginC Source C file												*
 * Copyright (c) Originlab Corp.	2006										*
 * All Rights Reserved															*
 * 																				*
 * Modification Log:															*
 * Sim 06-19-2009 QA80-13808 NOT_SWITCH_INPUT_WHEN_ACTIVE_SHEET_CHANGED			*
 * Sim 06-19-2009 QA80-4584 UPDATE_OK_AND_APPLY_BUTTON_STATUS_FOR_AUTO_UPDATE_SUPPORT
 * Sim 06-22-2009 QA80-4584-P3 DISABLE_OK_APPLY_WHEN_CONDITION_IS_EMPTY			*
 * Sim 06-23-2009 QA81-13345 REFIX_UPDATE_ROW_SEL_AFTER_COL_VALUE_CHANGE		*
 * Sophy 8/6/2009 RESIZE_OUTPUT_NODE_ON_RESIZE_DIALOG							*
 * Sophy 8/7/2009 v8.1088 EXTRACT_WKS_DATA_SAVE_RECALCULATE_MODE_TO_SOURCE_SHEET*
 *	YuI 10/15/09 QA70-13230-P6 EXTRACT_WKS_DATA_FROM_NUMERICALLY_NAMED_WORKSHEET*
 *	Jasmine 11/26/09 AUTO_CORRECT_INVALID_ALIAS_WHEN_ADD_FROM_COLUMN_LIST		*
 *	Folger 11/27/09 LOCALIZE_SCRIPT_EDIT_HINT									*
 *	Kyle 02/10/2010 QA80-15100 DATE_TIME_COLUMN_SHOW_<_>_AT_OPERATION_LIST		*
 *	Kyle 02/22/2010 QA80-15100-P2 PASS_THE_CURRENT_COLUMN_DISPLAY_TO_TIME_LT_FUNCTION
 *	Kyle 05/04/2010 QA80-15100-S1 ADD_FRAC_AND_INT_AS_EXAMPLE_FUNCTIONS_FOR_DATA_TIME_FORMAT_DATA
 *	Jasmine 09/10/10 RUNTIME_ERROR_IF_CHECK_LOCAL_VECTOR						*
 *	Folger 10/14/2010 ORG-1257-P1 RENAME_EXTRAC_WKS_DATA_TO_QUERY_WKS			*
 *	Folger 10/15/2010 ORG-1258 ADD_SELECT_OPTION_IN_WORKSHEET_QUERY				*
 *	Folger 10/27/2010 ORG-1258-P1 REDUNDANT_ERROR_MESSAGE_DUMP_WHEN_CHOOSE_HIGHLIGHT_COLOR_OR_SELECT
 *------------------------------------------------------------------------------*/
 
#include <Origin.h>

#include <..\OriginLab\DialogEx.h>
#include <..\OriginLab\ColumnList.h>
#include <..\OriginLab\FunctionsMenu.h>
#include <..\Originlab\XFunctionEx.h>
#include <xfutils.h>
//#include <..\OriginLab\ListMenu.h>
#include "ListMenu.h"
#include "ExtractWksData.h"
#include "ExtractWksDataDlg.h"

#define STR_COL_LIST_TOOL_TIPS		_L("Right-click for more options")  ///Jasmine 01/10/07, show tootips in ColumnList     
///------ Folger 10/14/2010 ORG-1257-P1 RENAME_EXTRAC_WKS_DATA_TO_QUERY_WKS
//#define STR_EXTRACT_DATA_DLG_NAME	_L("Extract Worksheet Data")
#define	STR_DLG_NAME				"Worksheet Query"
#define STR_EXTRACT_DATA_DLG_NAME	_L("Worksheet Query")
///------ End RENAME_EXTRAC_WKS_DATA_TO_QUERY_WKS

#define MIN_GAP                         5

//#define IS_EXISTING_VAR m_VarList.HasRows()

///---Sim 06-19-2009 QA80-13808 NOT_SWITCH_INPUT_WHEN_ACTIVE_SHEET_CHANGED
/*
BOOL ExtractDataDlg::OnActiveLayerChange()
{
	if( !IsInitReady() )
		return false;
	
	Worksheet wks = Project.ActiveLayer();
	//if( IsReady() && wks )
	if( wks )
	{
		// Sim, to improve
		// block active event of generate new worksheet from this dialog
		// should be improved to prevent active event sending, but we still have not good idea for this case
		// Sim, no need to do
		//if ( m_strBlockNewWks != wks_get_book_sheet_name(wks) )
		{
			//save the setting in dialog to the old worksheet
			string strOld = wks_get_book_sheet_name(m_wks);
			string strNew = wks_get_book_sheet_name(wks);
			if( strOld != strNew ) //we should also check if the worksheet's changed
			{
				// Sim, to do
				// Show warning to save setting
				SetDlgToWksSetting();
				
				SetWorksheet(wks);
				GetWksSettingToDlg();
				m_DynaCntrlExtractMethod.Update(DYNACONTROL_UPDATE_BITS);
				
				//enableCondition( IS_EXISTING_VAR );
				
				//m_vnRowIndices.RemoveAll();
				//m_trLastExtract.Reset();
				m_extwks.ClearCache();
			}
		}
	}
	
	// Sim, no need to do
	//m_strBlockNewWks.Empty();
	return TRUE;
}
*/
///---END QA80-13808 NOT_SWITCH_INPUT_WHEN_ACTIVE_SHEET_CHANGED
///---Sim 06-23-2009 QA81-13345 REFIX_UPDATE_ROW_SEL_AFTER_COL_VALUE_CHANGE
BOOL ExtractDataDlg::OnOriginModify(OriginObject obj, int nKind)
{
	m_extwks.ClearCache();
	return TRUE;	
}
///---END QA81-13345 REFIX_UPDATE_ROW_SEL_AFTER_COL_VALUE_CHANGE

BOOL ExtractDataDlg::OnDestroy()
{
	saveColListPos();
	
	if(m_pDlgMenu)
		delete m_pDlgMenu;
	m_ColList.OnDestroy();
	m_VarList.OnDestroy();
	ResizeDialog::OnDestroy();
	
	if ( m_bDeleteOnDestroy )
		delete this;
	return TRUE;
}

BOOL ExtractDataDlg::OnClickOK()
{	
	//Sim, need improve for XF body will apply again
	//Control ctrl = GetItem(IDC_APPLY_BTN);///Jasmine 07/26/06 RECORD_CHANGE
	//if(ctrl.Enable)
		//OnApply(ctrl);
	if ( !GetDlgSetting(&m_settings) )
		return FALSE;
	
	if ( !m_bFromAutoUpdate )
	{
		XFunction xf;
		Tree trXF;
		if ( !xf.Load(&trXF, "wextract", 0, true, false, true) )
			return error_report("Can't load xfunction wextract.oxf");
		
		Tree trRoot;
		TreeNode trGUI;
		//Tree trGUI;
		
		if ( !xf.GetGUI(trRoot, trGUI) )
			return error_report("Failed to load xfunction gui tree");
		if ( !GetGUI(trGUI) )
			return error_report("Failed to update xfunction gui tree");
		if ( !xf.SetGUI(trGUI) )
			return error_report("Failed to set xfunction gui tree");
		
		if ( 0 != xf.ExecuteLabTalk(NULL, NULL, NULL, 0, NULL, LTXF_EXECUTE, trGUI.AutoUpdate.nVal) )
			return error_report("Failed to execute xfunction wextract.oxf");		
	}
	
	SetDlgToWksSetting();
	return true;
}

BOOL ExtractDataDlg::OnClickCancel()
{
	// Sim, to do
	// Show warning to save setting
	SetDlgToWksSetting();
	return true;
}

BOOL ExtractDataDlg::OnShowMenu(UINT nResIDCtrl, int nx, int ny)
{
	if(IDC_COLUMN_LIST_GRID != nResIDCtrl)
		return TRUE;
	
	vector<int> vnCols = { 	COL_CHECK_BOX,
							//COL_PROPERTIES_LONG_NAME, 
							COL_PROPERTIES_PLOT_DESIGNATION,
							COL_PROPERTIES_FORMAT,
							COL_PROPERTIES_FIRST_VALUE
							};
	vector<bool> vbCheck;
	for(int ii = 0; ii < vnCols.GetSize(); ii++)
		vbCheck.Add( !m_ColList.IsColHidden(vnCols[ii]) );
	
	//ColumnListMenu	clm(vnCols, vbCheck);
	ColumnListMenu clm(vnCols, vbCheck, !m_bFromAutoUpdate);
	int nCmdID = clm.TrackPopupResMenu(0,  nx, ny, GetSafeHwnd());
	if ( nCmdID > 0 )
	{
		switch (nCmdID)
		{
		case EXTRACT_CHECK_ALL:
			m_ColList.Check(-1);
			break;
		case EXTRACT_UNCHECK_ALL:
			m_ColList.Check(-1, false);
			break;
		default:
			m_ColList.HideCol(nCmdID, !m_ColList.IsColHidden(nCmdID)); // toggle between show and hide
			
			//resize col list
			int nColListSize = m_ColList.GetColsWidth() + MIN_GAP;
			//ResizeColList(nColListSize - m_nLastColListWidth);
			m_nLastColListWidth = nColListSize;
			
			//Sim, to be improved
			InflateWindow(( m_bShowColList ? m_nLastColListWidth : 0 ) - GetColListWidth(), DIR_RIGHT);
			OnDlgResize(0, GetDlgExtent(false), GetDlgExtent(true));
		}
		
		return TRUE;
	}
	return FALSE;
	
}	

void ExtractDataDlg::OnBeforeEditColList(Control flxControl, long nRow, long nCol, BOOL* pCancel)
{
	m_ColList.BeforeEdit(flxControl, nRow, nCol, pCancel);
}
void ExtractDataDlg::OnBeforeEditVarList(Control flxControl, long nRow, long nCol, BOOL* pCancel)
{
	m_VarList.BeforeEdit(flxControl, nRow, nCol, pCancel);
}

void ExtractDataDlg::OnAfterEditColList(Control flxControl, int nRow, int nCol)
{
	//enableApply();	///Jasmine 07/26/06 RECORD_CHANGE
	notifySettingsUpdate(); ///---Sim 06-19-2009 QA80-4584 UPDATE_OK_AND_APPLY_BUTTON_STATUS_FOR_AUTO_UPDATE_SUPPORT
}
void ExtractDataDlg::OnAfterEditVarList(Control flxControl, int nRow, int nCol)
{
	m_VarList.AfterEdit(flxControl, nRow, nCol);
	//enableApply();	///Jasmine 07/26/06 RECORD_CHANGE
	notifySettingsUpdate(); ///---Sim 06-19-2009 QA80-4584 UPDATE_OK_AND_APPLY_BUTTON_STATUS_FOR_AUTO_UPDATE_SUPPORT
}
	
void ExtractDataDlg::OnColListRowChange(Control ctrl)
{
	vector<uint> vnRows;
	m_ColList.GetSelection(vnRows);
	bool bEnable = (vnRows.GetSize() >= 1);

	uint nButtonIDs[] = {IDC_SELECT_BTN, 0};
	EnableControls(nButtonIDs, bEnable);
}
void ExtractDataDlg::OnVarListRowChange(Control ctrl)
{
	vector<uint> vnRows;
	m_VarList.GetSelection(vnRows);
	bool bEnable = (vnRows.GetSize() >= 1);
	
	uint nButtonIDs[] = {IDC_ADD_BTN, IDC_REMOVE_SELECT_BTN, 0};
	EnableControls(nButtonIDs, bEnable);
}

void ExtractDataDlg::initMenu()
{
	HMENU 	hMenu = GetMenu(GetSafeHwnd());
	m_pDlgMenu = new ExtWksDataMenu(hMenu);
}

bool ExtractDataDlg::updateDlgToColumnSetting(ExtractWksDataSettings *pSettings)
{
	if ( NULL == pSettings )
	{
		ASSERT(FALSE);
		return false;
	}
	
	pSettings->vnCols.SetSize(0);
	
	for(int nRow = m_ColList.GetRowOffset(); nRow < m_ColList.GetRows(); nRow++)
	{
		int nCheck = atoi(m_ColList.GetCell(nRow, COL_CHECK_BOX));
		if(nCheck)
			pSettings->vnCols.Add(atoi(m_ColList.GetCell(nRow, COL_PROPERTIES_INDEX)) - 1);
	}

	return true;
}
bool ExtractDataDlg::updateColumnSettingToDlg(const ExtractWksDataSettings *pSettings)
{
	if ( NULL == pSettings )
	{
		ASSERT(FALSE);
		return false;
	}
	
	if( pSettings->vnCols.GetSize() )
	{
		m_ColList.Check(-1, false);
	}
	
	int nOffset = m_ColList.GetRowOffset();
	for(int ii = 0; ii < pSettings->vnCols.GetSize(); ii++)
	{
		m_ColList.Check(pSettings->vnCols[ii] + nOffset, true);
	}
	
	return true;
}

bool ExtractDataDlg::updateDlgToRowSetting(ExtractWksRowRange *pRowRange)
{
	if ( NULL == pRowRange )
	{
		ASSERT(FALSE);
		return false;
	}
	
	Control edFrom = GetItem(IDC_ROW_FROM_ED);
	Control edTo = GetItem(IDC_ROW_TO_ED);
	pRowRange->nRowFrom = atoi(edFrom.Text) - 1;
	pRowRange->nRowTo = atoi(edTo.Text) - 1;
	
	return true;
}
bool ExtractDataDlg::updateRowSettingToDlg(const ExtractWksRowRange *pRowRange)
{
	if ( NULL == pRowRange )
	{
		ASSERT(FALSE);
		return false;
	}
	
	Control edFrom = GetItem(IDC_ROW_FROM_ED);
	Control edTo = GetItem(IDC_ROW_TO_ED);
	
	edFrom.Text = pRowRange->nRowFrom + 1;
	edTo.Text = pRowRange->nRowTo + 1;
	
	return true;
}

BOOL ExtractDataDlg::OnLoadSysSampleCondition(int nID)
{
	return LoadAndUpdateRecentUsedCondition(nID, FROM_SYS_MENU);
}
BOOL ExtractDataDlg::OnLoadUserDefinedCondition(int nID)
{
	return LoadAndUpdateRecentUsedCondition(nID, FROM_USER_MENU);
}
BOOL ExtractDataDlg::OnLoadRecentUsedCondition(int nID)
{
	return LoadAndUpdateRecentUsedCondition(nID, FROM_MRU_MENU);
}

bool ExtractDataDlg::LoadAndUpdateRecentUsedCondition(int nID, int nFromMenu)
{
	Menu *pMenu = NULL;
	switch (nFromMenu)
	{
	case FROM_SYS_MENU:		pMenu = m_pDlgMenu->m_pConditionSysSample;			break;
	case FROM_USER_MENU:	pMenu = m_pDlgMenu->m_pConditionUserDefinedMenu;	break;
	case FROM_MRU_MENU:		pMenu = m_pDlgMenu->m_pConditionRecentListMenu;		break;
	default:				return false;
	}
	if ( NULL == pMenu )
		return false;
	string strCompositeName;
	pMenu->GetMenuString(nID, strCompositeName, MF_STRING);

	int nPathType;
	string strName;
	switch (nFromMenu)
	{
	case FROM_SYS_MENU:
		nPathType = ORIGIN_PATH_SYSTEM;
		strName = strCompositeName;
		break;
	case FROM_USER_MENU:
		nPathType = ORIGIN_PATH_USER;
		strName = strCompositeName;
		break;
	case FROM_MRU_MENU:
		strName = okutil_separate_composite_name(strCompositeName, &nPathType);
		break;
	default:
		return false;
	}
	//strCompositeName = okutil_composite_name_from_components(nPathType, NULL, strName);

	string strFile;
	switch ( nPathType )
	{
	case ORIGIN_PATH_SYSTEM:	strFile = STR_FAVORITE_CONDITION_FILE_SYS;		break;
	case ORIGIN_PATH_USER:		strFile = STR_FAVORITE_CONDITION_FILE;			break;
	default:					return false;
	}

	m_strCurConditionName = strName;
	if ( !loadCondition(strName, strFile) )
		return false;
	
	if ( !UpdateRecentUsedCondition(strName, nPathType) )
		return false;
	
	return true;
}

bool ExtractDataDlg::UpdateRecentUsedCondition(LPCSTR lpcszName, int nPathType) // = ORIGIN_PATH_USER
{
	string strCompositeName = okutil_composite_name_from_components(nPathType, NULL, lpcszName);

	if ( !( m_pDlgMenu->m_pConditionRecentListMenu->UpdateList(strCompositeName) ) )
		return false;

	GetWindow().Text = STR_EXTRACT_DATA_DLG_NAME + " - " + wks_get_book_sheet_name(m_wks) + " - " + strCompositeName;
	
	return true;
}

bool ExtractDataDlg::loadCondition(LPCSTR lpcszName, LPCSTR lpcszFile)
{
	string strCondSetting;
	int nRet = okutil_read_file_section(lpcszFile, lpcszName, &strCondSetting, NULL);
	if(nRet <= 0)
		return false;
	
	setConditionSetting(strCondSetting);
	//enableCondition(m_VarList.HasRows());  //set the Condition box can be edited.
		
	return true;
}
bool ExtractDataDlg::saveCondition(LPCSTR lpcszName, LPCSTR lpcszFile)
{
	int nRet = okutil_write_file_section(lpcszFile, lpcszName, getConditionSetting());
	if ( nRet <= 0 )
		return false;
	return true;
}


enum{
	CONDITION_SECTION_ALIAS,
	CONDITION_SECTION_IF,
	CONDITION_SECTION_BEFORE_LOOP,
	CONDITION_SECTION_BEFORE_IF,

	CONDITION_SECTION_TOTAL,
};

///---Sim 06-17-2009 FIX_SAVE_LOAD_CONDITION_FILE
//#define STR_COND_SCRIPT_SEP "\r\n##\r\n"

#define STR_COND_SCRIPT_SEP "##"
#define STR_COND_SCRIPT_CRLF "\r\n"
///---END FIX_SAVE_LOAD_CONDITION_FILE

string ExtractDataDlg::getConditionSetting()
{
	ExtractWksDataAlias *pAlias = &(m_settings.stAlias);
	ASSERT(pAlias);
	if ( !updateDlgToAliasSetting(pAlias) )
		return "";
	string strAliases = pAlias->GetAliasLines();
	
	ExtractWksDataCondition *pCondition = &(m_settings.stCondition);
	ASSERT(pCondition);
	if ( !updateDlgToConditionSetting(&(m_settings.stCondition)) )
		return "";
	string strCondition = pCondition->strCondition;
	string strBeforeLoop = pCondition->strBeforeLoop;
	string strBeforeIfCondition = pCondition->strBeforeIfCondition;


	vector<string> vsConditions(CONDITION_SECTION_TOTAL);
	vsConditions[CONDITION_SECTION_ALIAS] = strAliases;
	vsConditions[CONDITION_SECTION_IF] = strCondition;
	vsConditions[CONDITION_SECTION_BEFORE_LOOP] = strBeforeLoop;
	vsConditions[CONDITION_SECTION_BEFORE_IF] = strBeforeIfCondition;
	
	///---Sim 06-17-2009 FIX_SAVE_LOAD_CONDITION_FILE
	//string strConditionSetting = str_combine(vsConditions, STR_COND_SCRIPT_SEP);
	string strSep = STR_COND_SCRIPT_CRLF + STR_COND_SCRIPT_SEP + STR_COND_SCRIPT_CRLF; // for customer to view INI file	
	string strConditionSetting = str_combine(vsConditions, strSep);
	///---END FIX_SAVE_LOAD_CONDITION_FILE

	return strConditionSetting;
}

bool ExtractDataDlg::setConditionSetting(LPCSTR lpcszCondition)
{
	string strConditionSetting(lpcszCondition);
	///---Sim 06-17-2009 FIX_SAVE_LOAD_CONDITION_FILE
	//vector<string> vsConditions(CONDITION_SECTION_TOTAL);
	vector<string> vsConditions;
	///---END FIX_SAVE_LOAD_CONDITION_FILE
	str_separate(strConditionSetting, STR_COND_SCRIPT_SEP, vsConditions);
	
	int nSection = vsConditions.GetSize();
	if(nSection < 2) //must have the first two part: Alias and If Condition
		return false;
	if ( nSection < CONDITION_SECTION_TOTAL ) // fill empty string if no enough size
		vsConditions.SetSize(CONDITION_SECTION_TOTAL);
	
	string strAliases = vsConditions[CONDITION_SECTION_ALIAS];
	string strCondition = vsConditions[CONDITION_SECTION_IF];
	string strBeforeLoop = vsConditions[CONDITION_SECTION_BEFORE_LOOP];
	string strBeforeIfCondition = vsConditions[CONDITION_SECTION_BEFORE_IF];
	///---Sim 06-17-2009 FIX_SAVE_LOAD_CONDITION_FILE
	strAliases.TrimLeft(STR_COND_SCRIPT_CRLF);
	strAliases.TrimRight(STR_COND_SCRIPT_CRLF);
	strCondition.TrimLeft(STR_COND_SCRIPT_CRLF);
	strCondition.TrimRight(STR_COND_SCRIPT_CRLF);
	strBeforeLoop.TrimLeft(STR_COND_SCRIPT_CRLF);
	strBeforeLoop.TrimRight(STR_COND_SCRIPT_CRLF);
	strBeforeIfCondition.TrimLeft(STR_COND_SCRIPT_CRLF);
	strBeforeIfCondition.TrimRight(STR_COND_SCRIPT_CRLF);
	///---END FIX_SAVE_LOAD_CONDITION_FILE
	
	ExtractWksDataAlias *pAlias = &(m_settings.stAlias);
	ASSERT(pAlias);
	pAlias->SetAliasLines(strAliases);
	if ( !updateAliasSettingToDlg(pAlias) )
		return false;
	
	ExtractWksDataCondition *pCondition = &(m_settings.stCondition);
	ASSERT(pCondition);
	pCondition->strCondition = strCondition;
	pCondition->strBeforeLoop = strBeforeLoop;
	pCondition->strBeforeIfCondition = strBeforeIfCondition;
	if ( !updateConditionSettingToDlg(pCondition) )
		return false;

	return true;
}

bool ExtractDataDlg::updateDlgToConditionSetting(ExtractWksDataCondition *pCondition)
{
	//updateDlgToAliasSetting();

	//ExtractWksDataCondition *pCondition = &(m_settings.stCondition);
	ASSERT(pCondition);
	pCondition->strCondition = m_edExpression.Text;

	return true;
}
bool ExtractDataDlg::updateConditionSettingToDlg(const ExtractWksDataCondition *pCondition)
{
	//updateAliasSettingToDlg();
	
	//ExtractWksDataCondition *pCondition = &(m_settings.stCondition);
	ASSERT(pCondition);
	m_edExpression.Text = pCondition->strCondition;

	return true;	
}

bool ExtractDataDlg::updateDlgToAliasSetting(ExtractWksDataAlias *pAlias)
{
	ASSERT(pAlias);
	
	pAlias->vsAliasNames.SetSize(0);
	pAlias->vnCols.SetSize(0);
	
	for( int ii = m_VarList.GetRowOffset(); ii < m_VarList.GetRows(); ii++ )
	{
		pAlias->vsAliasNames.Add(m_VarList.GetCell(ii, COL_PROPERTIES_ALIAS));
		pAlias->vnCols.Add(m_VarList.GetColumnIndex(ii));
	}

	return true;
}
bool ExtractDataDlg::updateAliasSettingToDlg(const ExtractWksDataAlias *pAlias)
{
	//ExtractWksDataAlias *pAlias = &(m_settings.stAlias);
	ASSERT(pAlias);
	
	int nCols = m_ColList.GetRows() - m_ColList.GetRowOffset();
	
	vector<string> vsInValid, vsRepeat, vsMissing;
	m_VarList.ClearAll();
	int nSize = pAlias->vsAliasNames.GetSize();
	for(int ii = 0; ii < nSize; ii++)
	{
		string strAliasNames = pAlias->vsAliasNames[ii];
		int nColIndex = pAlias->vnCols[ii];
		addAliasToDlg(nColIndex, strAliasNames, vsInValid, vsRepeat);
		///Jasmine 09/10/10 RUNTIME_ERROR_IF_CHECK_LOCAL_VECTOR, vsMissing is local variable and no need to check its validity
		//if( nColIndex > nCols && vsMissing != NULL )//col isn't in wks
		if( nColIndex > nCols )
		///End RUNTIME_ERROR_IF_CHECK_LOCAL_VECTOR
			vsMissing.Add(strAliasNames);
	}
	
	showAliasWarning(vsInValid, vsRepeat, vsMissing);

	return true;
}
///Jasmine 11/26/09 AUTO_CORRECT_INVALID_ALIAS_WHEN_ADD_FROM_COLUMN_LIST
//bool ExtractDataDlg::addAliasToDlg(int nColIndex, LPCSTR lpcszAliasName, vector<string> &vsInValid, vector<string> &vsRepeat) // = NULL, NULL
bool ExtractDataDlg::addAliasToDlg(int nColIndex, LPCSTR lpcszAliasName, vector<string> &vsInValid/* = NULL*/, vector<string> &vsRepeat/* = NULL*/, bool bAutoCorrect/* = false*/) 
///End AUTO_CORRECT_INVALID_ALIAS_WHEN_ADD_FROM_COLUMN_LIST
{
	string strAliasName(lpcszAliasName);
	///Jasmine 11/26/09 AUTO_CORRECT_INVALID_ALIAS_WHEN_ADD_FROM_COLUMN_LIST
	//int nRow = m_VarList.AddRow(nColIndex - 1, strAliasName); // in this prototype, target index base on 0
	int nRow = m_VarList.AddRow(nColIndex - 1, strAliasName, bAutoCorrect);
	///End AUTO_CORRECT_INVALID_ALIAS_WHEN_ADD_FROM_COLUMN_LIST
	
	if( !is_good_C_identifier(strAliasName, 0) && vsInValid != NULL )
		vsInValid.Add(strAliasName);
	if( m_VarList.CheckAliasReused(strAliasName, nRow) > -1 && vsRepeat != NULL )
		vsRepeat.Add(strAliasName);

	return ( nRow >= 0 );
}

void ExtractDataDlg::showAliasWarning(const vector<string> &vsInValid, const vector<string> &vsRepeat, const vector<string> &vsMissing)// = NULL, NULL, NULL
{
	string strInvalidWarning, strRepeatWarning, strMissingWarning;
	if( vsInValid && vsInValid.GetSize() > 0 )
	{
		strInvalidWarning.SetTokens(vsInValid, ',');
		strInvalidWarning = strInvalidWarning + ": "+_L("invalid name!")+"\n";
	}
	if( vsRepeat && vsRepeat.GetSize() > 0 )
	{
		strRepeatWarning.SetTokens(vsRepeat, ',');
		strRepeatWarning = _L("Alias")+": " + strRepeatWarning + " "+_L("are repeated!")+"\n";
	}
	if( vsMissing && vsMissing.GetSize() > 0 )
	{
		strMissingWarning.SetTokens(vsMissing, ',');
		strMissingWarning = _L("The columns of these alias are missing in current worksheet")+": " + strMissingWarning + "\n";
	}
	if(lstrlen(strInvalidWarning) || lstrlen(strRepeatWarning) || lstrlen(strMissingWarning))
		MessageBox(GetSafeHwnd(), strInvalidWarning + strRepeatWarning + strMissingWarning, _L("Attention!"), MB_OK);
}

BOOL ExtractDataDlg::OnSaveCondition()
{
	if( !m_edExpression.Enable )
		return FALSE;
	
	if(m_strCurConditionName.IsEmpty())
		return OnSaveConditionAs();
	//if(IDNO == MessageBox(GetSafeHwnd(), _L("Do you want to overwrite")+" "+ m_strCurConditionName +"?", _L("Attention!"), MB_YESNO))
		//return FALSE;
	//m_strExpression = m_edExpression.Text;
	return saveCondition(m_strCurConditionName, STR_FAVORITE_CONDITION_FILE);
}
BOOL ExtractDataDlg::OnSaveConditionAs()
{
	if( !m_edExpression.Enable )
		return FALSE;
	
	//load saved names
	vector<string> vsNames;
	//okutil_get_file_sections(STR_FAVORITE_CONDITION_FILE, &vsKeyNames);
	m_pDlgMenu->m_pConditionUserDefinedMenu->GetList(vsNames);
	string strNameList;
	strNameList.SetTokens(vsNames, '|');
	if(!strNameList.IsEmpty())
		strNameList.Insert(0,"|");

	//get name to save
	string strName;
	GETN_TREE(trSaveAs)
	GETN_STR(Name, _L("Condition Name"), "")	GETN_EDIT_DISPLAY_WIDTH_RANGE( "30-30" )
	if(!strNameList.IsEmpty())
	{
		GETN_STR_COMBO(strNameList)
		_tmpSubNode.strVal = m_strCurConditionName;
	}
	if(!GetNBox(trSaveAs, _L("Save Condition As..."), _L("Input name for new condition"), NULL, NULL, GetSafeHwnd()))
		return FALSE;
	strName	= trSaveAs.Name.strVal;
	strName.TrimLeft();	strName.TrimRight();
	if(strName.IsEmpty())
		return FALSE;
	
	int nIndex = vsNames.Find(strName);
	if( -1 < nIndex ) // existing name
	{
		if ( IDNO == MessageBox(GetSafeHwnd(), _L("Do you want to overwrite")+" "+ vsNames[nIndex] +"?", _L("Attention!"), MB_YESNO) )
			return FALSE;
	}
	
	m_strCurConditionName = strName;
	
	//save in ini file
	if ( !saveCondition(strName, STR_FAVORITE_CONDITION_FILE) )
		return FALSE;
	
	//add to Load Condition Menu
	if( nIndex < 0 ) //new condition name
	{
		m_pDlgMenu->m_pConditionUserDefinedMenu->UpdateList(strName);
	}
	
	if ( !UpdateRecentUsedCondition(strName) )
		return FALSE;
	
	return TRUE;
}

BOOL ExtractDataDlg::OnEditScripts()
{
	string strBeforeLoop = m_settings.stCondition.strBeforeLoop;
	string strBeforeIfCondition = m_settings.stCondition.strBeforeIfCondition;

	GETN_TREE(tr)
	GETN_HELPID(IDD_EXTRACT_WKS_DATA_EDIT_SCRIPT)
	GETN_MULTILINE_TEXT(BeforeLoop, _L("Script Before Select Data Loop"), strBeforeLoop)	
		GETN_EDIT_DISPLAY_WIDTH_RANGE( "50-50" )
		GETN_OPTION_MUTILINE_TEXT_BOX(false, "2-15", true)
	GETN_MULTILINE_TEXT(BeforeIfCondition, _L("Script Before If Condition"), strBeforeIfCondition)
		GETN_EDIT_DISPLAY_WIDTH_RANGE( "50-50" )
		GETN_OPTION_MUTILINE_TEXT_BOX(false, "2-15", true)
	///------ Folger 11/27/09 LOCALIZE_SCRIPT_EDIT_HINT
	//GETN_MULTILINE_TEXT(tips,	"Run the Script Before Selected data loop.\n\
								Loop over all rows defined by the start and end values provided by user. \nFor each column whose row index is i:\n\
									\tRun the Script Before If Condition;\n\
									\tTest the condition, for data in row i\n\
									\tExtract data if the condition is true;\n\
									\tEnd extraction;\n\
								End loop;", "") GETN_HINT
	string		str;
	ocu_load_err_msg_str(IDS_EXTRACT_WKS_DATA_SCRIPT_EDIT_HINT, &str);
	///------ End LOCALIZE_SCRIPT_EDIT_HINT
	GETN_MULTILINE_TEXT(tips, str, "") GETN_HINT
		
	if(!GetNBox(tr, _L("Edit Scripts"), NULL, NULL, NULL, GetSafeHwnd()))
		return FALSE;
	
	m_settings.stCondition.strBeforeLoop = tr.BeforeLoop.strVal;
	m_settings.stCondition.strBeforeIfCondition = tr.BeforeIfCondition.strVal;
	
	notifySettingsUpdate(); ///---Sim 06-19-2009 QA80-4584 UPDATE_OK_AND_APPLY_BUTTON_STATUS_FOR_AUTO_UPDATE_SUPPORT
	
	return TRUE;
}

BOOL ExtractDataDlg::OnSelFunction(int nID)
{
	WksFunctionsMenu *pWksFunctionsMenu = m_pDlgMenu->m_pWksFunctionsMenu;
	if ( NULL == pWksFunctionsMenu )
	{
		ASSERT(FALSE);
		return false;
	}
	
	string strLabel;
	pWksFunctionsMenu->GetMenuString(nID, strLabel, MF_STRING);
	pWksFunctionsMenu->UpdateFuncHistoryList(strLabel);

	string strFormula = pWksFunctionsMenu->GetFunctionString(nID);
	insertStrToCondition(strFormula, true);
	return true;
}

BOOL ExtractDataDlg::OnClickSel(Control ctrl)
{	
	vector<uint> vnRows;
	if( m_ColList.GetSelection(vnRows) < 1 )
		return FALSE;

	// find the leftmost column
	int nMinIndex = m_ColList.GetColumnIndex(vnRows[0]) - 1;
	vector<string> vsInvalid, vsRepeat;
	for(int ii = 0; ii < vnRows.GetSize(); ii++)
	{
		int nColIndex = m_ColList.GetColumnIndex(vnRows[ii]);
		addAliasToDlg(nColIndex, NULL, vsInvalid, vsRepeat, true);	///Jasmine 11/26/09 AUTO_CORRECT_INVALID_ALIAS_WHEN_ADD_FROM_COLUMN_LIST
		
		if(nColIndex < nMinIndex)
			nMinIndex = nColIndex;
	}	
	m_VarList.SelRow(m_VarList.GetRows() - 1);
	
	wks_scroll_into_view(m_wks, nMinIndex);
	
	//enableCondition();
	notifySettingsUpdate(); ///---Sim 06-19-2009 QA80-4584 UPDATE_OK_AND_APPLY_BUTTON_STATUS_FOR_AUTO_UPDATE_SUPPORT
	
	showAliasWarning(vsInvalid, vsRepeat);
	
	return TRUE;
}
BOOL ExtractDataDlg::OnClickRemoveSel(Control ctrl)
{
	vector<uint> vnRemovedRows;
	vector<int> vnCanceledIndices;
	vector<string> vsInUsedAliases;
	int nSize = m_VarList.GetSelection(vnRemovedRows);
	for(int ii = 0; ii < nSize; ii++)
	{
		string strAliasName = m_VarList.GetCell(vnRemovedRows[ii], COL_PROPERTIES_ALIAS);
		if( lstrlen(strAliasName) && checkVarInCondition(strAliasName) ) //column alias is uesed in condition
		{
			vsInUsedAliases.Add(strAliasName);
			vnCanceledIndices.Add(ii);
		}
	}
	if( vnCanceledIndices.GetSize() > 0 )
	{
		string strWarning;
		strWarning.SetTokens(vsInUsedAliases, ',');
		if( OM_RETURN_YES != OptionalMessage("WxtRemoveAliasInUse", MB_OK, strWarning) )
			vnRemovedRows.RemoveAt(vnCanceledIndices);
	}	
	
	int nSelRow = m_VarList.GetSelectedRow();
	m_VarList.RemoveRows(vnRemovedRows);
	m_VarList.SelRow(nSelRow);
	
	//enableCondition(m_VarList.HasRows());
	notifySettingsUpdate(); ///---Sim 06-19-2009 QA80-4584 UPDATE_OK_AND_APPLY_BUTTON_STATUS_FOR_AUTO_UPDATE_SUPPORT
	
	return true;	
}
bool ExtractDataDlg::checkVarInCondition(LPCSTR lpcszVar)
{
	string strCondition = m_edExpression.Text;
	int nPos = strCondition.Find(lpcszVar, 0); 
	return ( 0 <= nPos );
}

BOOL ExtractDataDlg::OnClickHideColGridList(Control ctrl)
{
	ShowHideColList(); // toggler
	return true;
}

BOOL ExtractDataDlg::OnApply(Control ctrl)
{
	//SetReady(false);

	//updateDlgToAliasSetting();
	//updateDlgToConditionSetting();
	//setExtractMethodTree(&(m_settings->stMethod), m_trExtractMethod);
	if ( !GetDlgSetting(&m_settings) )
		return FALSE;
	
	/*
	m_extwks.SetSettings(m_settings);
	if ( !m_extwks.Extract(m_wks) )
	{
		return error_report("Error happen in extract_data");
	}

	m_strBlockNewWks = m_settings->stMethod.strWksSpecified;
	
	//GetItem(IDC_ROW_FOUND_TEXT).Text = _L("Rows Found")+" : "+ m_extwks->GetNumRows();
	updateSelRowNumber(m_extwks.GetNumRows());
	*/	
	if ( !Extract(&m_settings) )
		return FALSE;
	
	// keep last apply result for next apply
	m_extwks.GetSettings(m_settings);
	
	// Sim, apply to new sheet every times
	Worksheet wksInvalid;
	m_wksTo = wksInvalid;

	int nExtractTo = m_settings.stMethod.nMethod;
	if(nExtractTo == EXD_NEW_LAYER || nExtractTo == EXD_NEW_PAGE || nExtractTo == EXD_REPLACE)
	{
		///Sophy 8/7/2009 v8.1088 EXTRACT_WKS_DATA_SAVE_RECALCULATE_MODE_TO_SOURCE_SHEET
		//updateMethodSettingToDlg(&(m_settings.stMethod), &m_nAutoUpdateMode);
		///------ Folger 10/15/2010 ORG-1258 ADD_SELECT_OPTION_IN_WORKSHEET_QUERY
		//updateMethodSettingToDlg(&(m_settings.stMethod), &(m_settings.nRecalMode));
		updateMethodSettingToDlg(&(m_settings.stMethod), &(m_settings.stRecalculate));
		///------ End ADD_SELECT_OPTION_IN_WORKSHEET_QUERY
		///end EXTRACT_WKS_DATA_SAVE_RECALCULATE_MODE_TO_SOURCE_SHEET
		m_DynaCntrlExtractMethod.Update(DYNACONTROL_UPDATE_BITS);
	}

	SetDlgToWksSetting();
	//enableApply(false);	///Jasmine 07/26/06 RECORD_CHANGE
	notifySettingsUpdate(false); ///---Sim 06-19-2009 QA80-4584 UPDATE_OK_AND_APPLY_BUTTON_STATUS_FOR_AUTO_UPDATE_SUPPORT

	//SetReady();
	return TRUE;
}

BOOL ExtractDataDlg::OnClickTest(Control ctrl)
{
	// Sim, to do improve more
	//updateDlgToAliasSetting();
	//updateDlgToConditionSetting();
	//setExtractMethodTree(&(m_settings->stMethod), m_trExtractMethod);
	if ( !GetDlgSetting(&m_settings) )
		return FALSE;

	ExtractWksDataSettings settings;
	settings = m_settings;
	settings.stMethod.nMethod = EXD_TEST;

	/*
	m_extwks.SetSettings(m_settings);
	if ( !m_extwks.Extract(m_wks) )
	{
		return error_report("Error happen in extract_data");
	}
	
	//GetItem(IDC_ROW_FOUND_TEXT).Text = _L("Rows Found")+" : "+ m_extwks.GetNumRows();
	updateSelRowNumber(m_extwks.GetNumRows());
	*/	
	if ( !Extract(&settings) )
		return FALSE;
	
	return TRUE;
}

bool ExtractDataDlg::Extract(const ExtractWksDataSettings *pSettings)
{
	if ( NULL == pSettings )
	{
		ASSERT(FALSE);
		return false;
	}
	
	m_extwks.SetSettings(*pSettings);
	if ( !m_extwks.Extract(m_wks, m_wksTo) )
	{
		return error_report("Error happen in extract_data");
	}
	
	// Sim, no need to do
	//m_strBlockNewWks = pSettings->stMethod.strWksSpecified;
	
	updateSelRowNumber(m_extwks.GetNumRows());
	
	return true;
}

///Jasmine 08/18/06 KEEP_INDEX_TO_SAVE_TIME

/*
///Folger 04/11/07 ADD_COLOR_SPECIFIER
//bool ExtractDataDlg::extractData(Worksheet& wks, const TreeNode& trNew, int nExtractTo, string& strNew, int* pnRows)// = NULL,  = NULL
bool ExtractDataDlg::extractData(Worksheet& wks, const TreeNode& trNew, int nExtractTo, string& strNew, int* pnRows, int* pnColor)
///End ADD_COLOR_SPECIFIER
{
	if(!wks)
		return error_report("The source worksheet is invlid!");
	
	if( nExtractTo < 0 || nExtractTo >= EXD_SIZE)
		return error_report("Input nCmd error!");
	///Jasmine 08/21/06 TIME_REGISTER
	DWORD dw = GetTickCount();	
	getRowIndices(wks, trNew, m_vnRowIndices);
	double dTime1 = (GetTickCount()-dw)/1000.0;
	m_trLastExtract.Replace(trNew, true);
	if(pnRows)
		*pnRows = m_vnRowIndices.GetSize();
	vector<uint> 	vnCols;
	vnCols = trNew.Cols.nVals;
	dw = GetTickCount();
	
	///Folger 04/11/07 ADD_COLOR_SPECIFIER
//	if( !show_extract_data(wks, m_vnRowIndices, vnCols, nExtractTo, strNew) )
	if( !show_extract_data(wks, m_vnRowIndices, vnCols, nExtractTo, strNew, pnColor) )
	///End ADD_COLOR_SPECIFIER
		return error_report("Error in _show_extract_data");
	double dTime2 = (GetTickCount()-dw)/1000.0;
	/#
	Note nWnd("Time");
	if(!nWnd)
	{
		nWnd.Create();
		nWnd.Rename("Time");
	}
	nWnd.Text += "\nSelectRows = " + (string)dTime1 + "\nExtract = " + (string)dTime2;
	#/
	///End TIME_REGISTER
	return wks.PutBinaryStorage(STR_WKS_EXD_SETTINGS, trNew);
}
*/
/*
int ExtractDataDlg::getRowIndices(Worksheet& wks, const TreeNode& trNew, vector<uint>&	vnRowIndices)
{
	if(conditionChange(trNew) || variableDefChange(trNew))
	{
		vnRowIndices.RemoveAll();
		return select_rows(wks, trNew, vnRowIndices);
	}
	int nNewFrom, nNewTo, nOldFrom, nOldTo, nTemp;
	nNewFrom 	= trNew.Rows.From.nVal;
	nNewTo		= trNew.Rows.To.nVal;
	nOldFrom 	= m_trLastExtract.Rows.From.nVal;
	nOldTo 		= m_trLastExtract.Rows.To.nVal;
	if(nNewFrom > nNewTo)//make sure from < to
	{
		nTemp = nNewFrom;
		nNewFrom = nNewTo;
		nNewTo = nTemp;
	}
	if(nOldFrom > nOldTo)
	{
		nTemp = nOldFrom;
		nOldFrom = nOldTo;
		nOldTo = nTemp;
	}
	if(nNewFrom > nOldFrom)
		remove_vector(vnRowIndices, nOldFrom, (nNewFrom > nOldTo)? nOldTo : nNewFrom - 1);
	if(nNewTo < nOldTo)
		remove_vector(vnRowIndices, (nOldFrom > nNewTo)? nOldFrom : nNewTo + 1, nOldTo);
	if(nNewFrom < nOldFrom)
	{
		vector<uint> vnTemp;
		Tree trTemp;
		trTemp = trNew.Clone(true);
		trTemp.Rows.From.nVal = nNewFrom;
		trTemp.Rows.To.nVal = (nOldFrom > nNewTo)? nNewTo : nOldFrom - 1;
		select_rows(wks, trTemp, vnTemp);
		vnRowIndices.Append(vnTemp);
		if(vnRowIndices.GetSize())	
			vnRowIndices.Sort();
	}
	if(nNewTo > nOldTo)
	{
		vector<uint> vnTemp;
		Tree trTemp;
		trTemp = trNew.Clone(true);
		trTemp.Rows.From.nVal = (nNewFrom > nOldTo)? nNewFrom : nOldTo + 1;
		trTemp.Rows.To.nVal = nNewTo;
		select_rows(wks, trTemp, vnTemp);
		vnRowIndices.Append(vnTemp);
		if(vnRowIndices.GetSize())	
			vnRowIndices.Sort();
	}
	return vnRowIndices.GetSize();
}
bool ExtractDataDlg::conditionChange(const TreeNode& trNew)
{
	if(!m_trLastExtract.Condition.IsValid())
		return true;
	string strOld, strNew;
	int ii = 0;
	while(ii < 3)
	{
		switch(ii)
		{
		case 0:
			strOld = m_trLastExtract.Condition.Expression.strVal;
			strNew = trNew.Condition.Expression.strVal;
			break;
		case 1:
			strOld = m_trLastExtract.Condition.BeforeLoop.strVal;
			strNew = trNew.Condition.BeforeLoop.strVal;
			break;
		case 2:
			strOld = m_trLastExtract.Condition.BeforeIfCondition.strVal;
			strNew = trNew.Condition.BeforeIfCondition.strVal;
			break;
		default:
			return true;
		}
		strOld.TrimLeft();	strOld.TrimRight();
		strNew.TrimLeft();	strNew.TrimRight();
		if(strOld.CompareNoCase(strNew))
			return true;
		ii++;
	}
	return false;
}
bool ExtractDataDlg::variableDefChange(const TreeNode& trNew)
{
	if(!m_trLastExtract.Condition.IsValid())
		return true;
	vector<uint> vnOld, vnNew, vnIndeces;
	vector<string> vsOld, vsNew;
	vnOld = m_trLastExtract.Condition.Cols.nVals;
	vsOld = m_trLastExtract.Condition.Alias.strVals;
	vnOld.Sort(SORT_ASCENDING, TRUE, vnIndeces);
	vsOld.Reorder(vnIndeces);
	
	vnNew = trNew.Condition.Cols.nVals;
	vsNew = trNew.Condition.Alias.strVals;
	vnNew.Sort(SORT_ASCENDING, TRUE, vnIndeces);
	vsNew.Reorder(vnIndeces);
	
	string strOld, strNew;
	for(int ii=0; ii<vnOld.GetSize(); ii++)
	{
		string strTemp;
		strTemp.Format("%s = %d", vsOld[ii], vnOld[ii]);
		strOld += strTemp + ";";
	}
	strOld.TrimRight(';');
	for(ii=0; ii<vnOld.GetSize(); ii++)
	{
		string strTemp;
		strTemp.Format("%s = %d", vsNew[ii], vnNew[ii]);
		strNew += strTemp + ";";
	}
	strNew.TrimRight(';');
	if(strOld.CompareNoCase(strNew))
		return true;	
	return false;
}
///End KEEP_INDEX_TO_SAVE_TIME
*/

string _get_current_date_str()
{
	SYSTEMTIME st;
	GetSystemTime(&st);              // gets current time
	double dDate;
	SystemTimeToJulianDate(&dDate, &st);
	return get_date_str(dDate, LDF_SHORT);
}

///Kyle 02/10/2010 QA80-15100 DATE_TIME_COLUMN_SHOW_<_>_AT_OPERATION_LIST
///Kyle 02/22/2010 QA80-15100-P2 PASS_THE_CURRENT_COLUMN_DISPLAY_TO_TIME_LT_FUNCTION
//static string _get_current_time_str()
static string _get_current_time_str(int nFormat)
///End PASS_THE_CURRENT_COLUMN_DISPLAY_TO_TIME_LT_FUNCTION
{
	SYSTEMTIME st;
	get_current_time(st, true);
	double dDate;
	SystemTimeToJulianDate(&dDate, &st);
	///Kyle 02/22/2010 QA80-15100-P2 PASS_THE_CURRENT_COLUMN_DISPLAY_TO_TIME_LT_FUNCTION
	//return get_time_str(dDate, 2);		// HH:mm:ss
	return get_time_str(dDate, nFormat);		// HH:mm:ss
	///End PASS_THE_CURRENT_COLUMN_DISPLAY_TO_TIME_LT_FUNCTION
}
///End DATE_TIME_COLUMN_SHOW_<_>_AT_OPERATION_LIST

///Kyle 02/22/2010 QA80-15100-P2 PASS_THE_CURRENT_COLUMN_DISPLAY_TO_TIME_LT_FUNCTION
//string ExtractDataDlg::getNewConditionLine(int nType, LPCSTR lpcszAlias) // = OKCOLTYPE_NUMERIC, = NULL
string ExtractDataDlg::getNewConditionLine(int nType, int nSubFormat, LPCSTR lpcszCustomDisp, LPCSTR lpcszAlias) // = OKCOLTYPE_NUMERIC, = 0, = NULL, = NULL
///End PASS_THE_CURRENT_COLUMN_DISPLAY_TO_TIME_LT_FUNCTION
{
	GETN_TREE(tr)
		
	string strAlias(lpcszAlias);
	string strFuncList;
	if ( !strAlias.IsEmpty() )
		strFuncList += "|" + strAlias;
		
	switch(nType)
	{
	case OKCOLTYPE_NUMERIC:
	case OKCOLTYPE_TEXT_NUMERIC:
		strFuncList += "|abs(" + strAlias + ")";
		strFuncList += "|exp(" + strAlias + ")";
		strFuncList += "|ln(" + strAlias + ")";
		strFuncList += "|sqrt(" + strAlias + ")";
		strFuncList += "|sin(" + strAlias + ")";
		strFuncList += "|mod(" + strAlias + ",2)";
		strFuncList += "|" + strAlias + "[1]";
		GETN_STRLIST(Col, _L("Column Variable"), strAlias, strFuncList)	GETN_EDIT_DISPLAY_WIDTH_RANGE( "30-30" )
		GETN_STRLIST(Operator, _L("Operator"), ">", ">|>=|<|<=|==|!=")	GETN_EDIT_DISPLAY_WIDTH_RANGE( "30-30" )
		
		string strNull = "|0|NULL";
		if(OKCOLTYPE_TEXT_NUMERIC == nType)
			strNull += "|\"--\"|\"\"";
		GETN_STRLIST(Val, _L("Value"), "0", strNull)					GETN_EDIT_DISPLAY_WIDTH_RANGE( "30-30" )
		break;
	default:
		string strList = "|\"*\"|\"?\"|\"--\"|\"\"", strDefault = "\"*\"";
		switch(nType)
		{
		case OKCOLTYPE_TIME:
			///Kyle 02/10/2010 QA80-15100 DATE_TIME_COLUMN_SHOW_<_>_AT_OPERATION_LIST
			//strDefault = "\"00:00:00\"";
			///Kyle 02/22/2010 QA80-15100-P2 PASS_THE_CURRENT_COLUMN_DISPLAY_TO_TIME_LT_FUNCTION
			//strDefault = "time(" + _get_current_time_str() + ")";
			strDefault.Format("time(%s, %d)", _get_current_time_str(nSubFormat), nSubFormat);
			///End PASS_THE_CURRENT_COLUMN_DISPLAY_TO_TIME_LT_FUNCTION
			///End DATE_TIME_COLUMN_SHOW_<_>_AT_OPERATION_LIST
			strList = "|" + strDefault + strList;
			break;
		case OKCOLTYPE_DATE:
			strDefault = "date(" + _get_current_date_str() + ")";
			strList = "|" + strDefault + strList;
			break;
		case OKCOLTYPE_MONTH:
			
			break;
		case OKCOLTYPE_WEEKDAY:
			
			break;
		}
		///Kyle 05/04/2010 QA80-15100-S1 ADD_FRAC_AND_INT_AS_EXAMPLE_FUNCTIONS_FOR_DATA_TIME_FORMAT_DATA
		if( OKCOLTYPE_TIME==nType || OKCOLTYPE_DATE==nType )
		{
			strFuncList += "|frac(" + strAlias + ")";
			strFuncList += "|int(" + strAlias + ")";
		}
		///End ADD_FRAC_AND_INT_AS_EXAMPLE_FUNCTIONS_FOR_DATA_TIME_FORMAT_DATA
		GETN_STRLIST(Col, _L("Column Variable"), strAlias, strFuncList)	GETN_EDIT_DISPLAY_WIDTH_RANGE( "30-30" )
		///Kyle 02/10/2010 QA80-15100 DATE_TIME_COLUMN_SHOW_<_>_AT_OPERATION_LIST
		//GETN_STRLIST(Operator, _L("Operator"), "==" , "|==|!=") 		GETN_EDIT_DISPLAY_WIDTH_RANGE( "30-30" )
		string strOperators = (OKCOLTYPE_DATE==nType || OKCOLTYPE_TIME==nType) ? ">|>=|<|<=|==|!=" : "|==|!=";
		GETN_STRLIST(Operator, _L("Operator"), "==", strOperators) 		GETN_EDIT_DISPLAY_WIDTH_RANGE( "30-30" )
		///End DATE_TIME_COLUMN_SHOW_<_>_AT_OPERATION_LIST
		GETN_STRLIST(Val, _L("Value"), strDefault, strList)//GETN_STRLIST(Val, "Value", "\"--\"", "|\"--\"|\"\"")
																		GETN_EDIT_DISPLAY_WIDTH_RANGE( "30-30" )
		break;
	}		
	string strDesc;
	if(OKCOLTYPE_NUMERIC != nType)//OKCOLTYPE_TEXT == nType || OKCOLTYPE_TEXT_NUMERIC == nType)
		strDesc = _L("\"*\" matches any substring; \"?\" matches any character");
	
	if(!GetNBox(tr, _L("if..."), strDesc, NULL, NULL, GetSafeHwnd()))
		return "";
	
	return tr.Col.strVal + tr.Operator.strVal + tr.Val.strVal;
}

BOOL ExtractDataDlg::OnClickAdd(Control ctrl)
{
	int nFormat;
	///Kyle 02/22/2010 QA80-15100-P2 PASS_THE_CURRENT_COLUMN_DISPLAY_TO_TIME_LT_FUNCTION
	int nSubFormat;
	string strCustomDisplay;
	///End PASS_THE_CURRENT_COLUMN_DISPLAY_TO_TIME_LT_FUNCTION
	string strAlias;
	
	vector<uint> vnRows;
	if( m_VarList.GetSelection(vnRows) > 0 )
	{
		int nSelRow = vnRows[0];
		strAlias = m_VarList.GetCell(nSelRow, COL_PROPERTIES_ALIAS);
		
		int nCol = m_VarList.GetColumnIndex(nSelRow) - 1;
		///Kyle 02/22/2010 QA80-15100-P2 PASS_THE_CURRENT_COLUMN_DISPLAY_TO_TIME_LT_FUNCTION
		//nFormat = m_wks.Columns(nCol).GetFormat();
		Column col = m_wks.Columns(nCol);
		ASSERT(col);
		nFormat = col.GetFormat();
		nSubFormat = col.GetSubFormat();
		strCustomDisplay = col.GetCustomDisplay();
		///End PASS_THE_CURRENT_COLUMN_DISPLAY_TO_TIME_LT_FUNCTION
	}

	///Kyle 02/22/2010 QA80-15100-P2 PASS_THE_CURRENT_COLUMN_DISPLAY_TO_TIME_LT_FUNCTION, only time column will use nSubFormat now, date column can use the default date() function
	//string strCondition = getNewConditionLine(nFormat, strAlias);
	string strCondition = getNewConditionLine(nFormat, nSubFormat, strCustomDisplay, strAlias);
	///End PASS_THE_CURRENT_COLUMN_DISPLAY_TO_TIME_LT_FUNCTION
	insertStrToCondition(strCondition);
	return true;
}

BOOL ExtractDataDlg::OnClickRemove(Control ctrl)
{
	insertStrToCondition(NULL);
	return TRUE;
}
BOOL ExtractDataDlg::OnClickAnd(Control ctrl)
{
	insertStrToCondition(" AND ");
	return TRUE;	
}
BOOL ExtractDataDlg::OnClickOr(Control ctrl)
{
	insertStrToCondition(" OR ");
	return TRUE;	
}
BOOL ExtractDataDlg::OnClickNot(Control ctrl)
{
	insertStrToCondition(" ! ");
	return TRUE;	
}
BOOL ExtractDataDlg::OnClickLeftP(Control ctrl)
{
	insertStrToCondition(" ( ");
	return TRUE;	
}
BOOL ExtractDataDlg::OnClickRightP(Control ctrl)
{
	insertStrToCondition(" ) ");
	return TRUE;	
}

void ExtractDataDlg::insertStrToCondition(LPCSTR lpcsz, bool bFunctionStr)// = false
{	
	if(!m_edExpression.Enable)
		return;

	string strText(lpcsz);
	
	int nBackSel = 0;
	if ( bFunctionStr )
	{
		int nLastRightBracket = strText.ReverseFind(')');
		string strSel = m_edExpression.GetSelText();
		
		if ( nLastRightBracket >= 0 )
		{
			if ( !strSel.IsEmpty() )
			{
				strText.Insert(nLastRightBracket, strSel);
			}
			else
			{
				nBackSel = (strText.GetLength() - 1) - nLastRightBracket + 1;
			}
		}		
	}
	
	m_edExpression.ReplaceSel(strText, true);

	if ( nBackSel > 0 )
	{
		long nBegin, nEnd;
		m_edExpression.GetSel(nBegin, nEnd);
		nBegin -= nBackSel;
		nEnd -= nBackSel;		
		m_edExpression.SetSel(nBegin, nEnd);
	}
	
	SetFocus(m_edExpression.GetSafeHwnd());
}

BOOL ExtractDataDlg::OnClickAllRows(Control ctrl)
{
	if(!m_wks)
		return FALSE;
	
	GetItem(IDC_ROW_FROM_ED).Text = 1;
	GetItem(IDC_ROW_TO_ED).Text = m_wks.GetNumRows();
	return TRUE;
}

BOOL ExtractDataDlg::OnDblClickToSel(Control ctrl)
{
	OnClickSel(GetItem(IDC_SELECT_BTN));
	return true;
}

/*
BOOL ExtractDataDlg::OnDblClickToAdd(Control ctrl)
{
	OnClickAdd(GetItem(IDC_ADD_BTN));
	return true;
}
*/

void ExtractDataDlg::updateSelRowNumber(string strNumber)// = "--"
{
	GetItem(IDC_ROW_FOUND_TEXT).Text = _L("Rows Found") + " : " + strNumber;
}

/*
void ExtractDataDlg::enableCondition(bool bEnable)// = true)
{
	m_edExpression.Enable = bEnable;
	vector<int> ids = {	IDC_REMOVE_BTN, IDC_BTN_AND, IDC_BTN_OR, 
						IDC_BTN_NOT, IDC_BTN_LEFT_P, IDC_BTN_RIGHT_P, 
						IDC_TEST_BTN, IDC_APPLY_BTN, IDOK};
	for(int ii = 0 ; ii < ids.GetSize(); ii++)
		GetItem(ids[ii]).Enable = m_edExpression.Enable;
	/// Hong 02/10/09 RECALCULATE_SUPPORT
	if ( m_tr ) // fail to support when recalculate
	{
		GetItem(IDC_APPLY_BTN).Enable = false;
	}
	/// end RECALCULATE_SUPPORT
}
*/

#define STR_SECTION_COL_LIST_WIDTH "COL_LIST_WIDTH"
#define STR_SECTION_COL_LIST_SHOW "COL_LIST_SHOW"

void ExtractDataDlg::saveColListPos()
{
	if ( !m_bShowColList )
		m_nLastColListWidth = -m_nLastColListWidth;
	
	SaveSetting(STR_SECTION_COL_LIST_WIDTH, m_nLastColListWidth, STR_EXTRACT_DATA_DLG_NAME);
}
void ExtractDataDlg::loadColListPos()
{
	int nColListSize = m_ColList.GetColsWidth() + MIN_GAP;
	m_nLastColListWidth = LoadSetting(STR_SECTION_COL_LIST_WIDTH, nColListSize, STR_EXTRACT_DATA_DLG_NAME);

	m_bShowColList = ( m_nLastColListWidth > 0 );
	m_nLastColListWidth = abs(m_nLastColListWidth);		
}
/*
void ExtractDataDlg::saveColListPos()
{
	SaveSetting(STR_SECTION_COL_LIST_WIDTH, m_nLastColListWidth, STR_EXTRACT_DATA_DLG_NAME);
	
	DWORD dwVal = m_bShowColList ? 1 : 0;
	SaveSetting(STR_SECTION_COL_LIST_SHOW, dwVal, STR_EXTRACT_DATA_DLG_NAME);
}
void ExtractDataDlg::loadColListPos()
{
	int nColListSize = m_ColList.GetColsWidth() + MIN_GAP;
	m_nLastColListWidth = LoadSetting(STR_SECTION_COL_LIST_WIDTH, nColListSize, STR_EXTRACT_DATA_DLG_NAME);

	DWORD dwVal = LoadSetting(STR_SECTION_COL_LIST_SHOW, -1, STR_EXTRACT_DATA_DLG_NAME);
	if ( -1 != dwVal )
		m_bShowColList = dwVal;
	else
	{	// for compatibility
		m_bShowColList = ( m_nLastColListWidth > 0 );
		m_nLastColListWidth = abs(m_nLastColListWidth);		
	}
}
*/

static void _check_show_extract_method(TreeNode& tr)
{
	tr.WksName.Show = (EXD_REPLACE == tr.ExtractTo.nVal);
	tr.ColFrom.Show = (EXD_REPLACE == tr.ExtractTo.nVal);
	
	tr.ColorList.Show = (EXD_COLOR == tr.ExtractTo.nVal);
}
///------ Folger 10/15/2010 ORG-1258 ADD_SELECT_OPTION_IN_WORKSHEET_QUERY
static void _check_enbale_auto_update(TreeNode& tr)
{
	BOOL	bEnable = ENABLE;
	switch ( tr.ExtractTo.nVal )
	{
	case EXD_COLOR:
	case EXD_TEST_EX:
		bEnable = FALSE;
	}
	tr.AutoUpdate.Enable = bEnable;
}
///------ End ADD_SELECT_OPTION_IN_WORKSHEET_QUERY
static bool _radio_event(TreeNode& myTree, int nRow, int nCol, TreeNode& trNode, DWORD dwCntrl, int nType, WndContainer& theDlg)
{
	if(nRow >= 0)
   	{
		//myTree.WksName.Show = SPECIFIED_SHEET == trNode.nVal;
		//myTree.ColorList.Show = COLOR_LIST == trNode.nVal;
		_check_show_extract_method(myTree);
		///------ Folger 10/15/2010 ORG-1258 ADD_SELECT_OPTION_IN_WORKSHEET_QUERY
		_check_enbale_auto_update(myTree);
		///------ End ADD_SELECT_OPTION_IN_WORKSHEET_QUERY
    	return true;
   	}
   	return false;
}

///------ Folger 10/15/2010 ORG-1258 ADD_SELECT_OPTION_IN_WORKSHEET_QUERY
#define		EXTRACT_OUTPUT_CHOICES		_L("Add a column of 1=true,0=false | Extract to New Worksheet | Extract to New Workbook | Extract to Specified Sheet | Fill with Specified Color | Select")
///------ End ADD_SELECT_OPTION_IN_WORKSHEET_QUERY

void ExtractDataDlg::constructMethodGetN(TreeNode& tr)
{
	GETN_USE(tr)
		GETN_LIST(NODE_NAME_AUTO_UPDATE, _L(STR_RECALCULATE), DEFAULT_AU_MODE, _L(STR_AU_COMBO)) GETN_ID(IDE_AUTO_UPDATE)
		GETN_SEPARATOR_LINE		
		
		///------ Folger 10/15/2010 ORG-1258 ADD_SELECT_OPTION_IN_WORKSHEET_QUERY
		//GETN_RADIO_INDEX(ExtractTo, 0, _L("Add a column of 1=true,0=false | Extract to New Worksheet | Extract to New Workbook | Extract to Specified Sheet | Fill with Specified Color") ) 
		GETN_RADIO_INDEX(ExtractTo, 0, EXTRACT_OUTPUT_CHOICES) 
		///------ End ADD_SELECT_OPTION_IN_WORKSHEET_QUERY
		GETN_OPTION_DISPLAY_FORMAT(DISPLAY_EDITOR_LEFT)
		GETN_OPTION_EVENT_EX(_radio_event)
		GETN_STR(WksName, _L("Worksheet Name"), "")
		GETN_NUM(ColFrom, _L("Column from"), 0)
			//GETN_ADD_AUTO(true)
		GETN_COLOR(ColorList, _L("Color"), 0)
		/// Hong 02/10/09 RECALCULATE_SUPPORT
		//GETN_STR(Range, "", "") GETN_HINT
		/// end RECALCULATE_SUPPORT

	TreeNode trNode = tr.ColFrom;
	octree_set_auto_support(&trNode, 1);
	
	tr.WksName.Show = false;
	tr.ColFrom.Show = false;
	tr.ColorList.Show = false;
	/// Hong 02/10/09 RECALCULATE_SUPPORT
	//tr.Range.Show = false;
}

///------ Folger 10/15/2010 ORG-1258 ADD_SELECT_OPTION_IN_WORKSHEET_QUERY
//bool ExtractDataDlg::updateDlgToMethodSetting(ExtractWksDataMethod *pMethod, int* pnAutoUpdateMode)
bool ExtractDataDlg::updateDlgToMethodSetting(ExtractWksDataMethod *pMethod, RecalculateSettings* pRecalculte)
///------ End ADD_SELECT_OPTION_IN_WORKSHEET_QUERY
{
	///------ Folger 10/15/2010 ORG-1258 ADD_SELECT_OPTION_IN_WORKSHEET_QUERY
	//if ( NULL == pMethod || NULL == pnAutoUpdateMode )
	if ( NULL == pMethod || NULL == pRecalculte )
	///------ End ADD_SELECT_OPTION_IN_WORKSHEET_QUERY
	{
		ASSERT(FALSE);
		return false;
	}

	TreeNode trExtractMethod = m_trExtractMethod;
	
	if ( trExtractMethod.NODE_NAME_AUTO_UPDATE )
	///------ Folger 10/15/2010 ORG-1258 ADD_SELECT_OPTION_IN_WORKSHEET_QUERY
		//*pnAutoUpdateMode = trExtractMethod.NODE_NAME_AUTO_UPDATE.nVal;
	{
		pRecalculte->nMode = trExtractMethod.NODE_NAME_AUTO_UPDATE.nVal;
		pRecalculte->nEnable = trExtractMethod.NODE_NAME_AUTO_UPDATE.Enable;
	}
	///------ End ADD_SELECT_OPTION_IN_WORKSHEET_QUERY

	pMethod->nMethod = trExtractMethod.ExtractTo.nVal;
	//pMethod->nColFilter = -1;
	pMethod->strWksSpecified = trExtractMethod.WksName.strVal;
	//int nAuto = 1;
	//trExtractMethod.ColFrom.GetAttribute(STR_ATTRIB_AUTO, nAuto);
	TreeNode trNode = trExtractMethod.ColFrom;
	int nAuto = octree_get_auto_support(&trNode);
	if ( 1 == nAuto )
		pMethod->nColFrom = -1;
	else
		pMethod->nColFrom = trExtractMethod.ColFrom.nVal - 1;
	pMethod->nColTo = -1;
	pMethod->nColor = trExtractMethod.ColorList.nVal;
	
	return true;
}
///------ Folger 10/15/2010 ORG-1258 ADD_SELECT_OPTION_IN_WORKSHEET_QUERY
//bool ExtractDataDlg::updateMethodSettingToDlg(const ExtractWksDataMethod *pMethod, const int* pnAutoUpdateMode)
bool ExtractDataDlg::updateMethodSettingToDlg(const ExtractWksDataMethod *pMethod, const RecalculateSettings* pRecalculte)
///------ End ADD_SELECT_OPTION_IN_WORKSHEET_QUERY
{
	///------ Folger 10/15/2010 ORG-1258 ADD_SELECT_OPTION_IN_WORKSHEET_QUERY
	//if ( NULL == pMethod || NULL == pnAutoUpdateMode )
	if ( NULL == pMethod || NULL == pRecalculte )
	///------ End ADD_SELECT_OPTION_IN_WORKSHEET_QUERY
	{
		ASSERT(FALSE);
		return false;
	}

	TreeNode trExtractMethod = m_trExtractMethod;
	
	if ( trExtractMethod.NODE_NAME_AUTO_UPDATE )
	///------ Folger 10/15/2010 ORG-1258 ADD_SELECT_OPTION_IN_WORKSHEET_QUERY
		//trExtractMethod.NODE_NAME_AUTO_UPDATE.nVal = *pnAutoUpdateMode;
	{
		trExtractMethod.NODE_NAME_AUTO_UPDATE.nVal = pRecalculte->nMode;
		trExtractMethod.NODE_NAME_AUTO_UPDATE.Enable = pRecalculte->nEnable;
	}
	///------ End ADD_SELECT_OPTION_IN_WORKSHEET_QUERY
	
	trExtractMethod.ExtractTo.nVal = pMethod->nMethod;
	//pMethod->nColFilter = -1;
	trExtractMethod.WksName.strVal = pMethod->strWksSpecified;
	TreeNode trNode = trExtractMethod.ColFrom;
	if ( pMethod->nColFrom >= 0 )
	{
		trExtractMethod.ColFrom.nVal = pMethod->nColFrom + 1;
		//trExtractMethod.ColFrom.Auto = 0;
		//trExtractMethod.ColFrom.SetAttribute(STR_ATTRIB_AUTO, 0);
		octree_set_auto_support(&trNode, 0);
	}
	else
	{
		trExtractMethod.ColFrom.nVal = 1;
		//trExtractMethod.ColFrom.Auto = 1;
		//trExtractMethod.ColFrom.SetAttribute(STR_ATTRIB_AUTO, 1);
		octree_set_auto_support(&trNode, 1);
	}
	//pMethod->nColTo = -1;
	trExtractMethod.ColorList.nVal = pMethod->nColor;

	//trExtractMethod.WksName.Show = SPECIFIED_SHEET == tr.ExtractTo.nVal;
	//trExtractMethod.ColorList.Show = COLOR_LIST == tr.ExtractTo.nVal;
	_check_show_extract_method(trExtractMethod);
	//tr.Range.SetAttribute(STR_LABEL_ATTRIB, m_tr.oy.strVal);
	//tr.Range.Show = true;
	
	return true;
}

bool ExtractDataDlg::GetDlgSetting(ExtractWksDataSettings *pSettings)
{
	if ( NULL == pSettings )
		return false;

	updateDlgToColumnSetting(pSettings);
	updateDlgToRowSetting(&(pSettings->stRowRange));
	updateDlgToAliasSetting(&(pSettings->stAlias));
	updateDlgToConditionSetting(&(pSettings->stCondition));
	//setExtractMethodTree(&(pSettings->stMethod), m_trExtractMethod);
	///Sophy 8/7/2009 v8.1088 EXTRACT_WKS_DATA_SAVE_RECALCULATE_MODE_TO_SOURCE_SHEET
	//updateDlgToMethodSetting(&(pSettings->stMethod), &m_nAutoUpdateMode);
	///------ Folger 10/15/2010 ORG-1258 ADD_SELECT_OPTION_IN_WORKSHEET_QUERY
	//updateDlgToMethodSetting(&(pSettings->stMethod), &(pSettings->nRecalMode));
	updateDlgToMethodSetting(&(pSettings->stMethod), &(pSettings->stRecalculate));
	///------ End ADD_SELECT_OPTION_IN_WORKSHEET_QUERY
	///end EXTRACT_WKS_DATA_SAVE_RECALCULATE_MODE_TO_SOURCE_SHEET

	return true;
}
bool ExtractDataDlg::SetDlgSetting(const ExtractWksDataSettings *pSettings)
{
	if ( NULL == pSettings )
		return false;

	updateColumnSettingToDlg(pSettings);
	updateRowSettingToDlg(&(pSettings->stRowRange));
	updateAliasSettingToDlg(&(pSettings->stAlias));
	updateConditionSettingToDlg(&(pSettings->stCondition));
	//getExtractMethodTree(m_trExtractMethod, &(pSettings->stMethod));
	///Sophy 8/7/2009 v8.1088 EXTRACT_WKS_DATA_SAVE_RECALCULATE_MODE_TO_SOURCE_SHEET
	//updateMethodSettingToDlg(&(pSettings->stMethod), &m_nAutoUpdateMode);
	///------ Folger 10/15/2010 ORG-1258 ADD_SELECT_OPTION_IN_WORKSHEET_QUERY
	//updateMethodSettingToDlg(&(pSettings->stMethod), &(pSettings->nRecalMode));
	updateMethodSettingToDlg(&(pSettings->stMethod), &(pSettings->stRecalculate));
	///------ End ADD_SELECT_OPTION_IN_WORKSHEET_QUERY
	///end EXTRACT_WKS_DATA_SAVE_RECALCULATE_MODE_TO_SOURCE_SHEET
	
	updateSelRowNumber();
	
	return true;
}

bool ExtractDataDlg::GetWksSettingToDlg()
{
	Tree tr;
	//if ( m_wks.GetBinaryStorage(STR_WKS_EXD_SETTINGS, tr) && !tr.IsEmpty() )
	if ( load_extract_settings_to_wks_storage(m_wks, tr) )
	{
		if ( !m_settings.SetTree(tr) )
			return false;
	}
	else
	{
		//m_settings.Reset();
		ExtractWksDataSettings settings; // defualt;
		m_settings = settings;
		
		int 			nFrom, nTo;
		m_wks.GetBounds(nFrom, 0, nTo, -1);
		m_settings.stRowRange.nRowFrom = nFrom;
		m_settings.stRowRange.nRowTo = nTo;
	}

	return SetDlgSetting(&m_settings);
}
bool ExtractDataDlg::SetDlgToWksSetting()
{
	Tree tr;
	if ( !GetDlgSetting(tr) ) 
		return false;
	//return m_wks.PutBinaryStorage(STR_WKS_EXD_SETTINGS, tr);
	return save_extract_settings_to_wks_storage(m_wks, tr);
}
				
bool ExtractDataDlg::SetWorksheet(const Worksheet& wks)
{
	string strBookSheet = wks_get_book_sheet_name(wks);
	m_ColList.Update(strBookSheet);	
	m_VarList.SetDatasheet(strBookSheet);
	m_wks = wks;
	//m_strWks = strBookSheet;
	
	///---Sim 06-19-2009 QA80-13808 NOT_SWITCH_INPUT_WHEN_ACTIVE_SHEET_CHANGED
	GetWindow().Text = STR_EXTRACT_DATA_DLG_NAME + " - " + wks_get_book_sheet_name(m_wks);
	///---END QA80-13808 NOT_SWITCH_INPUT_WHEN_ACTIVE_SHEET_CHANGED
	
	return true;
}

bool ExtractDataDlg::GetGUI(TreeNode& trGUI)
{
	if(!trGUI)
		return false;
	
	// settings
	Tree trSettings;
	//if(!GetDlgSetting(trSettings))
		//return false;
	if( !m_settings.GetTree(trSettings) )
		return false;
	trGUI.settings.Replace(trSettings, true, true);

	if ( !m_bFromAutoUpdate )
	{
		// input
		DataRange		dr;
		vector<int>		vnColIndices;
		vnColIndices = m_settings.vnCols;
		int				nR1 = m_settings.stRowRange.nRowFrom,
						nR2 = m_settings.stRowRange.nRowTo;
		for ( int ii = 0; ii < vnColIndices.GetSize(); ii++ )
		{
			dr.Add("X", m_wks, nR1, vnColIndices[ii], nR2, vnColIndices[ii]);
		}
		/// YuI 10/15/09 QA70-13230-P6 EXTRACT_WKS_DATA_FROM_NUMERICALLY_NAMED_WORKSHEET
		//	string			strDesc = dr.GetDescription();
		//	strDesc.Replace("\r\n", ',');
		//	trGUI.iy.strVal = "(" + strDesc + ")";
		string strRange;
		if( dr.GetRangeString(strRange) )
			trGUI.iy.strVal = strRange;
		/// end EXTRACT_WKS_DATA_FROM_NUMERICALLY_NAMED_WORKSHEET
	
		// output
		bool			bCanRecalculate = true;
		string			strOutput;
		
		ExtractWksDataMethod & stMethod = m_settings.stMethod;
		switch ( stMethod.nMethod + EXD_ADD_ROW_INDEX )
		{
		case EXD_ADD_ROW_INDEX:
			///---Sim 06-19-2009 QA80-4584 UPDATE_OK_AND_APPLY_BUTTON_STATUS_FOR_AUTO_UPDATE_SUPPORT
			int nColFilter = m_settings.stMethod.nColFilter;
			if ( nColFilter < 0 )
				strOutput.Format("[%s]%s!<new name:=\"%s\">", STR_INPUT, STR_INPUT, "Filter");
			else
				strOutput.Format("[%s]%s!%d", STR_INPUT, STR_INPUT, nColFilter + 1);
			///---END QA80-4584 UPDATE_OK_AND_APPLY_BUTTON_STATUS_FOR_AUTO_UPDATE_SUPPORT
			break;
		case EXD_NEW_LAYER:
			strOutput.Format("[%s]<new name:=\"%s\">", STR_INPUT, STR_EXTRACTED_FROM + m_wks.GetName());
			break;
		case EXD_NEW_PAGE:
			strOutput.Format("[%s]<new name:=\"%s\">", STR_NEW, m_wks.GetName());
			break;
		case EXD_REPLACE:
		{
			/*
			Page		pg;
			m_wks.GetParent(pg);
			string		strSheet = m_wks.GetName();
			ASSERT(pg);
			if ( 0 != strSheet.CompareNoCase(stMethod.strWksSpecified) )
			{
				//Sim, need to improve, similar with ExtractWksData::Extract()
				string strNew = stMethod.strWksSpecified;
				Worksheet wksTo;
				if ( strNew.IsEmpty() )
				{
					wksTo = m_wks;
				}
				else
				{
					///Folger 04/16/07 MODIFY_FUNCTION
					if ( !attach_or_create_sheet(wksTo, strNew, CREATE_VISIBLE|CREATE_LOAD_1ST_LAYER_ONLY) )
					{
						string strPage = Project.ActiveLayer().GetPage().GetName();
						strNew = "[" + strPage + "]" + strNew;
						attach_or_create_sheet(wksTo, strNew, CREATE_VISIBLE|CREATE_LOAD_1ST_LAYER_ONLY);
					}
					///End Folger 04/16/07 MODIFY_FUNCTION
				}
				
				int nC1 = stMethod.nColFrom;
				int nC2 = stMethod.nColTo;
				if ( nC1 < 0 && wksTo )
				{
					nC1 = wks_find_empty_column(wksTo);
					if ( nC1 < 0 )
						nC1 = wksTo.GetNumCols();
				}
				if ( nC1 < 0 )
				{
					nC1 = 0;
				}
				//Sim, always auto fit
				//if ( nC2 < 0 )
					nC2 = nC1 + vnColIndices.GetSize() - 1;
		
				//strOutput.Format("[%s]%s!%d:%d", pg.GetName(), stMethod.strWksSpecified, nC1 + 1, nC2 + 1);
				strOutput.Format("%s!%d:%d", wks_get_book_sheet_name(wksTo), nC1 + 1, nC2 + 1);
			}
			*/
			string strNew = get_completed_book_sheet_name(stMethod.strWksSpecified);
			Worksheet wksTo;
			get_dest_wks(wksTo, strNew, m_wks);
			if ( !is_same_layer(m_wks, wksTo) )
			{
				int nC1, nC2;
				get_specified_col_index(nC1, nC2, m_settings, wksTo);
				
				strOutput.Format("%s!%d:%d", strNew, nC1 + 1, nC2 + 1);
			}
			else
			{
				strOutput = STR_OPTIONAL;
				bCanRecalculate = false;
			}
			break;
		}
		case EXD_COLOR:
		///------ Folger 10/27/2010 ORG-1258-P1 REDUNDANT_ERROR_MESSAGE_DUMP_WHEN_CHOOSE_HIGHLIGHT_COLOR_OR_SELECT
		case EXD_TEST_EX:
		///------ End REDUNDANT_ERROR_MESSAGE_DUMP_WHEN_CHOOSE_HIGHLIGHT_COLOR_OR_SELECT
		default:
			strOutput = STR_OPTIONAL;
			bCanRecalculate = false;
			break;
		}
	
		trGUI.oy.strVal = strOutput;
		//trGUI.AutoUpdate.nVal = bCanRecalculate ? AU_ON_COMMAND : AU_NONE;
		///Sophy 8/7/2009 v8.1088 EXTRACT_WKS_DATA_SAVE_RECALCULATE_MODE_TO_SOURCE_SHEET
		//trGUI.NODE_NAME_AUTO_UPDATE.nVal = bCanRecalculate ? m_nAutoUpdateMode : AU_NONE;
		trGUI.NODE_NAME_AUTO_UPDATE.nVal = bCanRecalculate ? trSettings.RecalMode.nVal : AU_NONE;
		///end EXTRACT_WKS_DATA_SAVE_RECALCULATE_MODE_TO_SOURCE_SHEET
		///------ Folger 10/27/2010 ORG-1258-P1 REDUNDANT_ERROR_MESSAGE_DUMP_WHEN_CHOOSE_HIGHLIGHT_COLOR_OR_SELECT
		//if ( !bCanRecalculate )
		if ( !bCanRecalculate && (AU_NONE != trSettings.RecalMode.nVal && ENABLE == trSettings.RecalMode.Enable) )
		///------ End REDUNDANT_ERROR_MESSAGE_DUMP_WHEN_CHOOSE_HIGHLIGHT_COLOR_OR_SELECT
		{
			warning_msg_box(CER_NOT_ESTABLISH_AUTO_UPDATE, false);
		}		
	}

	return true;
	
}

bool ExtractDataDlg::SetGUI(const TreeNode& trGUI)
{
	if(!trGUI)
		return false;
	
	// settings
	//if(!SetDlgSetting(trGUI.settings))
	if( !m_settings.SetTree(trGUI.settings) )
		return false;

	if ( trGUI.NODE_NAME_AUTO_UPDATE )
		///Sophy 8/7/2009 v8.1088 EXTRACT_WKS_DATA_SAVE_RECALCULATE_MODE_TO_SOURCE_SHEET
		//m_nAutoUpdateMode = trGUI.NODE_NAME_AUTO_UPDATE.nVal;
	///------ Folger 10/15/2010 ORG-1258 ADD_SELECT_OPTION_IN_WORKSHEET_QUERY
		//m_settings.nRecalMode = trGUI.NODE_NAME_AUTO_UPDATE.nVal;
	{
		m_settings.stRecalculate.nMode = trGUI.NODE_NAME_AUTO_UPDATE.nVal;
		m_settings.stRecalculate.nEnable = trGUI.NODE_NAME_AUTO_UPDATE.Enable;
	}
	///------ End ADD_SELECT_OPTION_IN_WORKSHEET_QUERY
		///end EXTRACT_WKS_DATA_SAVE_RECALCULATE_MODE_TO_SOURCE_SHEET
	
	// input
	DataRange		drInput;
	if ( okxf_init_range_from_string(&drInput, trGUI.iy.strVal) )
	{
		int nC1, nC2;
		Worksheet wks;
		if ( drInput.GetRange(wks, nC1, nC2) && wks )
			m_wks = wks;
	}
	
	// output
	DataRange		drOutput;
	if ( okxf_init_range_from_string(&drOutput, trGUI.oy.strVal) )
	{
		int nC1, nC2;
		Worksheet wks;
		if ( drOutput.GetRange(wks, nC1, nC2) && wks )
			m_wksTo = wks;
	}

	return true;
}


bool ExtractDataDlg::GetDlgSetting(TreeNode& tr, DWORD dwOptions) // = 0
{
	if ( !GetDlgSetting(&m_settings) )
		return false;

	if ( !m_settings.GetTree(tr) )
		return false;

	return true;		
}
bool ExtractDataDlg::SetDlgSetting(const TreeNode& tr, DWORD dwOptions) // = 0
{
	if ( !m_settings.SetTree(tr) )
		return false;

	if ( !SetDlgSetting(&m_settings) )
		return false;

	return true;
}




BOOL ExtractDataDlg::OnInitDialog()
{
	ResizeDialog::OnInitDialog(IDC_EDIT_CONDITION, STR_EXTRACT_DATA_DLG_NAME);		
	InitToolBar(IDR_EXTRACT_DATA_MENU);
	/// ML 11/5/2007 PROOPER_MENU_LANGUAGE_WHEN_MENU_COMES_FROM_DLG_RESOURCE
	SetLangMenu(IDR_EXTRACT_DATA_MENU);
	/// end PROOPER_MENU_LANGUAGE_WHEN_MENU_COMES_FROM_DLG_RESOURCE

	//Worksheet wks = Project.ActiveLayer();
	Worksheet wks = m_wks;
	if ( !wks )
	{
		//return error_report("The input worksheet is invalid");
		wks = Project.ActiveLayer();
	}
	// Hong, to do, need to init input too, need to init output option
	string				strWksName;
	strWksName = wks_get_book_sheet_name(wks);
	/*
	if ( m_tr.iy &&  !m_tr.iy.IsEmpty())
	{
		DataRange		dr;
		TreeNode		trInput = m_tr.iy;
		if ( okxf_resolve_tree_construct_range(&trInput, &dr) )			
		{
			Worksheet	wks;
			int			nC1, nC2;
			dr.GetRange(wks, nC1, nC2);
			if ( wks )
			{
				strWksName = wks.m_strBookSheet;
			}
		}
	}
	*/
	m_ColList.Init(IDC_COLUMN_LIST_GRID, *this, STR_EXTRACT_DATA_DLG_NAME, strWksName);
	m_ColList.SetToolTipsText(STR_COL_LIST_TOOL_TIPS);
	
 	m_VarList.Init(IDC_SEL_COLUMN_GRID, *this, NULL, strWksName);

	///---Sim 06-19-2009 QA80-4584 UPDATE_OK_AND_APPLY_BUTTON_STATUS_FOR_AUTO_UPDATE_SUPPORT
	///*
	//if ( m_tr ) // fail to support when recalculate
	//{
		//GetItem(IDC_APPLY_BTN).Enable = false;
	//}
	//*/
	//if ( m_bFromAutoUpdate )
	//{
		//GetItem(IDC_APPLY_BTN).Enable = false;
	//}
	///---END QA80-4584 UPDATE_OK_AND_APPLY_BUTTON_STATUS_FOR_AUTO_UPDATE_SUPPORT
	
	//if(!GetWorksheet())
		//return error_report("The input worksheet is invalid");
	if( !SetWorksheet(wks) )
		return error_report("The input worksheet is invalid");
 	
	if ( m_bFromAutoUpdate )
		m_ColList.EnableCheck(-1, false);
	
	initMenu();
 	GetItem(IDC_ADD_BTN).Enable = false;
	m_edExpression = GetItem(IDC_EDIT_CONDITION);
	
	//m_strExpression = "";
	
	//CheckRadioButton(IDC_RADIO_TO_WKS, IDC_RADIO_ADD_COL, IDC_RADIO_TO_WB);
			
	//GetWksSetting();
	//enableCondition(m_VarList.HasRows());
	
	constructMethodGetN(m_trExtractMethod);
	if ( !m_bFromAutoUpdate )
		GetWksSettingToDlg();
	else
		SetDlgSetting(&m_settings);
	
	if ( m_bFromAutoUpdate )
		tree_set_attribute_to_all_nodes(m_trExtractMethod, STR_ENABLE_ATTRIB, "0");
	
	m_DynaCntrlExtractMethod.CreateControl(GetItem(IDC_COLOR_MAP_GRID).GetSafeHwnd());
	m_DynaCntrlExtractMethod.SetTree(m_trExtractMethod, DYNALAYOUT_BACKGROUND_GRAY);
	
	notifySettingsUpdate(); ///---Sim 06-19-2009 QA80-4584 UPDATE_OK_AND_APPLY_BUTTON_STATUS_FOR_AUTO_UPDATE_SUPPORT
	
	return true;
}

void ExtractDataDlg::InflateWindow(int dx, int nDirection)
{
	Window win = GetWindow();
	RECT rWindow;
	win.GetWindowRect(&rWindow);
	switch (nDirection)
	{
	case DIR_LEFT:	rWindow.left = rWindow.left - dx;		break;
	case DIR_RIGHT:	rWindow.right = rWindow.right + dx;		break;
	}
	win.MoveWindow(&rWindow);
}
//bool ExtractDataDlg::IsColListShown()
//{
	//return GetItem(IDC_COLUMN_LIST_GRID).Visible;
//}
int ExtractDataDlg::GetColListWidth()
{
	RECT rCol;
	GetClientRect(GetItem(IDC_COLUMN_LIST_GRID), rCol);
	return rCol.right - rCol.left;	
}
//void ExtractDataDlg::SetColListWidth(int nColWidth)
//{
	//RECT rCol;
	//Control ctrl = GetItem(IDC_COLUMN_LIST_GRID);
	//GetClientRect(ctrl, rCol);
	//rCol.right = rCol.left + nColWidth;
	//MoveControl(ctrl, rCol);		
//}
/*
BOOL ExtractDataDlg::ResizeLeftRightPanel(int nLeftPanelInc, int nDirection)// = 0, DIR_RIGHT
{
	MoveControlsHelper	_temp(this);	///Jasmine 05/31/07 QA70-9799 DLG_RESIZE_PAINT_MESS

	InflateWindow(nLeftPanelInc, nDirection);

	SetColListWidth(GetColListWidth() + nLeftPanelInc);
	
	//RECT rOK;	
	//GetClientRect(GetItem(IDOK), rOK);
	//rCol.bottom = rOK.bottom;
	
	vector<int> ids = {	IDC_COLOR_MAP_GRID,
						IDOK, IDCANCEL, IDC_SELECT_BTN, IDC_REMOVE_SELECT_BTN,
						IDC_REMOVE_BTN, IDC_BTN_AND, IDC_BTN_OR, IDC_BTN_NOT, IDC_BTN_LEFT_P, IDC_BTN_RIGHT_P, IDC_DESCRIPTION_TEXT,		
						IDC_ADD_BTN, IDC_APPLY_BTN, IDC_TEST_BTN, IDC_EDIT_CONDITION, IDC_RADIO_TO_WKS, IDC_RADIO_ADD_COL, IDC_STATIC_EXTRACT, IDC_RADIO_TO_WB, IDC_RADIO_TO_SPEC, IDC_ED_SPECIFIED_WKS,
						IDC_ROW_TEXT, IDC_ROW_FROM_ED, IDC_ROW_TO_TEXT, IDC_ROW_TO_ED, IDC_STATIC_COL_TEST, IDC_STATIC_IF, IDC_STATIC_TEST_CONDITION, IDC_SEL_COLUMN_GRID, IDC_COL_HIDE_SHOW,
						IDC_ROW_FOUND_TEXT,
						IDC_ALL_ROWS_BTN
						};
	MoveControls(ids, nColWidthInc);
	return true;
}	
*/

void ExtractDataDlg::ShowHideColList()
{
	m_bShowColList = !m_bShowColList;

	int nWidthInc = m_bShowColList ? m_nLastColListWidth : -m_nLastColListWidth;
	OnDlgResize(RESIZE_TYPE_SHOW_HIDE_LEFT_PANEL, GetDlgExtent(false)+nWidthInc, GetDlgExtent(true));
	
	InflateWindow(nWidthInc, DIR_LEFT);
}

/*	
	void MoveRightControls(const vector<int> ids, int width, int height, int updown = 0) //updown = 0 up, updown = 1 down
	{
		RECT rr;
		Control ctrl;
		for(int ii = 0; ii < ids.GetSize(); ii++)
		{
			ctrl = GetItem(ids[ii]);
			GetClientRect(ctrl,rr);		
			rr.left = rr.left + width;
			rr.right = rr.right + width;
			if(1 == updown)
			{
				rr.top = rr.top + height;
				rr.bottom = rr.bottom + height;
			}
			MoveControl(ctrl,rr);	
		}
	}
*/

BOOL ExtractDataDlg::OnReady()
{
	SetInitReady();
	OnDlgResize(0, GetDlgExtent(false), GetDlgExtent(true));
	
	loadColListPos();
	int nWidthInc = ( m_bShowColList ? m_nLastColListWidth : 0 ) - GetColListWidth();
	
	int nType = m_bShowColList ? 0 : RESIZE_TYPE_SHOW_HIDE_LEFT_PANEL; // dialog default show left panel
	OnDlgResize(nType, GetDlgExtent(false)+nWidthInc, GetDlgExtent(true));

	InflateWindow(nWidthInc, DIR_RIGHT);
	return true;
}

///------ Folger 10/15/2010 ORG-1258 ADD_SELECT_OPTION_IN_WORKSHEET_QUERY
BOOL ExtractDataDlg::OnRestoreSize(DWORD dwSizeInfo)
{
	void * p = (void*)dwSizeInfo;
	DLGSIZEINFO *pSz = (DLGSIZEINFO*)p;
	
	string strDlgName = STR_DLG_NAME;
	lstrcpyn(pSz->szDialogName, strDlgName, MAXLINE);
	pSz->top = -1;
	pSz->left = -1;
	pSz->width = 540;
	pSz->height = 500;
	return TRUE;
}
///------ End ADD_SELECT_OPTION_IN_WORKSHEET_QUERY
	
BOOL ExtractDataDlg::OnDlgResize(int nType, int cx, int cy)
{
	if( !IsInitReady() )
		return false;		
	
	bool bChangeShowHide = ( RESIZE_TYPE_SHOW_HIDE_LEFT_PANEL == nType );		
		
	MoveControlsHelper	_temp(this);


	vector<uint> vnXOffsetIDs, vnYOffsetIDs;
	vector<uint> vnXOffsetRevisedIDs;

	vector<uint> vnBottomRightIDs = {IDOK, IDCANCEL, IDC_APPLY_BTN, IDC_TEST_BTN};
	vnXOffsetIDs.Append(vnBottomRightIDs);
	vnYOffsetIDs.Append(vnBottomRightIDs);

	vector<int> vnBottomIDs = {	IDC_COLOR_MAP_GRID,			///Folger 04/11/07 ADD_COLOR_SPECIFIER
								//IDC_RADIO_TO_WKS, IDC_RADIO_ADD_COL, IDC_STATIC_EXTRACT, IDC_RADIO_TO_WB, IDC_RADIO_TO_SPEC, IDC_ED_SPECIFIED_WKS,
								IDC_STATIC_EXTRACT,
								IDC_ROW_TEXT, IDC_ROW_FROM_ED, IDC_ROW_TO_TEXT, IDC_ROW_TO_ED,
								IDC_ROW_FOUND_TEXT	///Jasmine 08/16/06 OUTPUT_SELECTED_ROWS										
								};
	if ( m_bShowColList || bChangeShowHide )
	{
		vnXOffsetIDs.Append(vnBottomIDs);
		vnXOffsetRevisedIDs.Append(vnBottomIDs);
	}
	vnYOffsetIDs.Append(vnBottomIDs);

	//button : AND, OR, NOT, ( and )
	vector<uint> vnRightIDs = {IDC_DESCRIPTION_TEXT, IDC_ADD_BTN, IDC_REMOVE_BTN, IDC_BTN_AND, IDC_BTN_OR, IDC_BTN_NOT, IDC_BTN_LEFT_P, IDC_BTN_RIGHT_P};
	vnXOffsetIDs.Append(vnRightIDs);
	
	vector<uint> vnLeftIDs = {IDC_STATIC_IF, IDC_STATIC_TEST_CONDITION, IDC_EDIT_CONDITION, IDC_SEL_COLUMN_GRID, IDC_COL_HIDE_SHOW, IDC_SELECT_BTN, IDC_REMOVE_SELECT_BTN, IDC_STATIC_COL_TEST};
	if ( m_bShowColList || bChangeShowHide )
	{
		vnXOffsetIDs.Append(vnLeftIDs);
		vnXOffsetRevisedIDs.Append(vnLeftIDs);
	}

	int nGap = MIN_GAP;
	int nMoveHeight, nMoveWidth;
	Control ctrl;
	RECT rr, rRef;
	
	ctrl = GetItem(IDOK);
	GetClientRect(ctrl, rr);
	nMoveWidth = cx - nGap - rr.right;
	nMoveHeight = cy - nGap - rr.bottom;

	vnXOffsetIDs.Add(0);
	vnYOffsetIDs.Add(0);
	MoveControls(vnXOffsetIDs, nMoveWidth, 0);
	MoveControls(vnYOffsetIDs, 0, nMoveHeight);
	if ( m_bShowColList )
	{
		vnXOffsetRevisedIDs.Add(0);
		MoveControls(vnXOffsetRevisedIDs, getRevisedWidthForColListMinWidth(), 0);
	}

	resizeAllRowsButton(nGap);

	//column variables
	ctrl = GetItem(IDC_SEL_COLUMN_GRID);  
	GetClientRect(ctrl, rr);
	GetClientRect(GetItem(IDC_DESCRIPTION_TEXT), rRef);
	rr.right = rRef.left - nGap;
	MoveControl(ctrl, rr);
	
	//condition box
	ctrl = GetItem(IDC_EDIT_CONDITION);
	GetClientRect(ctrl, rr);
	GetClientRect(GetItem(IDC_REMOVE_BTN), rRef);
	rr.right = rRef.left - nGap;
	GetClientRect(GetItem(IDC_TEST_BTN), rRef);
	rr.bottom = rRef.top - nGap;
	MoveControl(ctrl,rr);
	
	///Sophy 8/6/2009 RESIZE_OUTPUT_NODE_ON_RESIZE_DIALOG
	//output group box
	ctrl = GetItem(IDC_COLOR_MAP_GRID);
	GetClientRect(ctrl, rr);
	GetClientRect(GetItem(IDC_EDIT_CONDITION), rRef);
	rr.right = rRef.right;
	MoveControl(ctrl, rr);
	///end RESIZE_OUTPUT_NODE_ON_RESIZE_DIALOG

	//column list grid
	ctrl = GetItem(IDC_COLUMN_LIST_GRID);
	GetClientRect(ctrl, rr);
	if ( m_bShowColList )
	{
		GetClientRect(GetItem(IDC_COL_HIDE_SHOW), rRef);
		rr.right = rRef.left - nGap;
		m_nLastColListWidth = rr.right - rr.left;
	}
	else
	{
		rr.right = rr.left;
	}
	rr.bottom = cy - nGap;
	MoveControl(ctrl, rr);
	
	vector<uint> vnVarCtrlIDs = {IDC_STATIC_COL, IDC_COLUMN_LIST_GRID, IDC_SELECT_BTN, IDC_REMOVE_SELECT_BTN};
	ShowControls(vnVarCtrlIDs, m_bShowColList);
	
	GetItem(IDC_COL_HIDE_SHOW).Text = m_bShowColList? ">>" : "<<";

	
	return true;
}

int ExtractDataDlg::getColListMinWidth()
{
	return 50; // 5 + 40 + 5, 5 is Gap
}

int ExtractDataDlg::getRevisedWidthForColListMinWidth()
{
	RECT rr;
	GetClientRect(GetItem(IDC_COL_HIDE_SHOW), rr);
	if ( rr.left < getColListMinWidth() )
		return getColListMinWidth() - rr.left;
	return 0;
}

void ExtractDataDlg::resizeAllRowsButton(int nGap)
{
	int nWidth, nHeight;
	RECT rr, rRef;
	
	Control ctrl = GetItem(IDC_ALL_ROWS_BTN);
	GetClientRect(ctrl, rr);			
	GetClientRect(GetItem(IDC_ROW_TO_ED), rRef);
	
	nWidth = rr.right - rr.left;
	nHeight = rr.bottom - rr.top;
	
	rr.left = rRef.right + nGap;
	rr.right = rr.left + nWidth;
	
	rr.top = rRef.top;
	rr.bottom = rRef.bottom;
	MoveControl(ctrl, rr);			
}

///---Sim 06-19-2009 QA80-4584 UPDATE_OK_AND_APPLY_BUTTON_STATUS_FOR_AUTO_UPDATE_SUPPORT
BOOL ExtractDataDlg::OnContentChange(Control ctrl)
{
	//enableApply();
	GetDlgSetting(&m_settings); ///---Sim 06-22-2009 QA80-4584-P3 DISABLE_OK_APPLY_WHEN_CONDITION_IS_EMPTY
	notifySettingsUpdate(); ///---Sim 06-19-2009 QA80-4584 UPDATE_OK_AND_APPLY_BUTTON_STATUS_FOR_AUTO_UPDATE_SUPPORT
	return TRUE;
}
///---END QA80-4584 UPDATE_OK_AND_APPLY_BUTTON_STATUS_FOR_AUTO_UPDATE_SUPPORT
///Jasmine 08/11/06 MAKE_FROM_LESS_THAN_TO
BOOL ExtractDataDlg::OnEDFromChange(Control ctrl)
{
	ctrl.Text = (string)CheckGetInvalidRowIndex(atoi(ctrl.Text), true);
	//enableApply(); 
	notifySettingsUpdate(); ///---Sim 06-19-2009 QA80-4584 UPDATE_OK_AND_APPLY_BUTTON_STATUS_FOR_AUTO_UPDATE_SUPPORT
	return TRUE;
}
BOOL ExtractDataDlg::OnEDToChange(Control ctrl)
{
	ctrl.Text = (string)CheckGetInvalidRowIndex(atoi(ctrl.Text), false);
	//enableApply(); 
	notifySettingsUpdate(); ///---Sim 06-19-2009 QA80-4584 UPDATE_OK_AND_APPLY_BUTTON_STATUS_FOR_AUTO_UPDATE_SUPPORT
	return TRUE;
}
///End MAKE_FROM_LESS_THAN_TO
int ExtractDataDlg::CheckGetInvalidRowIndex(int nRowIndex, bool bFrom)
{
	int nNumRows = m_wks.GetNumRows();
	if( nRowIndex < 1 || nRowIndex > nNumRows )
		nRowIndex = bFrom ? 1 : nNumRows;
	return nRowIndex;
}

void ExtractDataDlg::OnAfterValueChange(int nRow, DWORD lParam)
{
	//enableApply();
	///---Sim 06-19-2009 QA80-4584 UPDATE_OK_AND_APPLY_BUTTON_STATUS_FOR_AUTO_UPDATE_SUPPORT
	GetDlgSetting(&m_settings);
	notifySettingsUpdate();
	///---END QA80-4584 UPDATE_OK_AND_APPLY_BUTTON_STATUS_FOR_AUTO_UPDATE_SUPPORT
	m_DynaCntrlExtractMethod.Update(DYNACONTROL_UPDATE_BITS);
}

///---Sim 06-19-2009 QA80-4584 UPDATE_OK_AND_APPLY_BUTTON_STATUS_FOR_AUTO_UPDATE_SUPPORT
void ExtractDataDlg::notifySettingsUpdate(bool bDirty)// = true
{
	uint nBtnIds[] = {
		IDC_APPLY_BTN,
		IDOK,
		0};
	
	///---Sim 06-22-2009 QA80-4584-P3 DISABLE_OK_APPLY_WHEN_CONDITION_IS_EMPTY
	//EnableControls(nBtnIds, bDirty);
	bool bEnable = bDirty;
	
	if ( m_settings.stCondition.strCondition.IsEmpty() )
		bEnable = false;
	
	EnableControls(nBtnIds, bEnable);
	///---END QA80-4584-P3 DISABLE_OK_APPLY_WHEN_CONDITION_IS_EMPTY
	
	///Sophy 8/7/2009 v8.1088 EXTRACT_WKS_DATA_SAVE_RECALCULATE_MODE_TO_SOURCE_SHEET	
	//if ( AU_NONE != m_nAutoUpdateMode )
	///------ Folger 10/15/2010 ORG-1258 ADD_SELECT_OPTION_IN_WORKSHEET_QUERY
	//if ( AU_NONE != m_settings.nRecalMode )
	if ( AU_NONE != m_settings.stRecalculate.nMode && DISABLE != m_settings.stRecalculate.nEnable )
	///------ End ADD_SELECT_OPTION_IN_WORKSHEET_QUERY
	///end EXTRACT_WKS_DATA_SAVE_RECALCULATE_MODE_TO_SOURCE_SHEET
		GetItem(IDC_APPLY_BTN).Enable = false;
}
///---END UPDATE_OK_AND_APPLY_BUTTON_STATUS_FOR_AUTO_UPDATE_SUPPORT


bool ExtractDataBox(TreeNode& trGetN, HWND hWndParent = NULL, PEVENT_GETN pfnGetN = NULL)
{
	ExtractDataDlg myDlg();

	//int nRet = myDlg.DoModalEx(trGetN, hWndParent);
	
	//Sim, to do
	myDlg.SetGUI(trGetN);
	int nRet = myDlg.DoModalEx(hWndParent);
	if(IDOK == nRet)
	{
		//myDlg.UpdateEditTreeNode(trGetN);
		//Sim, to do
		myDlg.GetGUI(trGetN);
		return true;
	}
	return false;
}

void OpenExtractWksModelssDialog()
{
	ExtractDataDlg *pExtractDlg = new ExtractDataDlg;
	pExtractDlg->Create();
	// pExtractDlg will be deleted by itself when dialog close
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////
// for testing
/////////////////////////////////////////////////////////////////////////////////////////////////////////////
static bool init_from_selection(TreeNode &trGUI)
{
	TreeNode trInputData = trGUI.iy;
	int nErrorCode;
	bool bRet;
	if( !init_input_data_branch_from_selection(trInputData, 0, &nErrorCode) )
	{
		trInputData.SetAttribute(STR_ERROR_CODE_ATTRIB, nErrorCode);
		bRet = false;
	}
	else
	{
		trInputData.RemoveAttribute(STR_ERROR_CODE_ATTRIB);
		bRet = true;
	}
	trInputData.ID = 0x10000000;
	//trInputData.Range1.DataID = 0x0020000a;
	//trInputData.Range1.X.DataID = 0x00000033;
	//trInputData.Range1.Y.DataID = 0x00000034;
	//trInputData.Range1.Z.DataID = 0x00000036;
		
	return bRet;
}

// modal
void test_extract_wks_dlg()
{
	Tree trGUI;
	
	trGUI.AddNode("iy");
	init_from_selection(trGUI);
	
	trGUI.AddNode("oy");
	
	trGUI.AddNode("settings");
	ExtractWksDataSettings settings;
	settings.GetTree(trGUI.settings);	
	
	ExtractDataBox(trGUI);
	
	out_tree(trGUI);
}

// modeless
/*
static ExtractDataDlg* s_pExtractDlg = NULL;
int ExtractWksDataDlg(int nMsg)
{
	bool bClose = OMSG_CLOSE==nMsg? true:false;
	bool bUpdate = OMSG_UPDATE==nMsg? true:false;

	if(bClose)
	{
		if(s_pExtractDlg)
		{
			Window winDlg = s_pExtractDlg->GetWindow();
			if(winDlg)
				winDlg.SendMessage(WM_CLOSE);
			delete s_pExtractDlg;
			s_pExtractDlg = NULL;
		}
		return 0;
	}
	// open or update
	if(!s_pExtractDlg)
	{
		if(bUpdate)
			return 1;// not possible to update, since dialog not opened

		s_pExtractDlg = new ExtractDataDlg;
		s_pExtractDlg->Create(GetWindow(OGW_MDICLIENT));
	}
	if(bUpdate)
		;
	
	return 0;
}

void test_extract_wks_dlg_modeless_open()
{
	ExtractWksDataDlg(OMSG_OPEN);
}
void test_extract_wks_dlg_modeless_close()
{
	ExtractWksDataDlg(OMSG_CLOSE);
}
*/
void test_extract_wks_dlg_modeless()
{
	Tree trGUI;
	
	trGUI.AddNode("iy");
	init_from_selection(trGUI);
	
	trGUI.AddNode("oy");
	
	trGUI.AddNode("settings");
	ExtractWksDataSettings settings;
	settings.GetTree(trGUI.settings);	
	
	ExtractDataDlg *pExtractDlg = new ExtractDataDlg;
	pExtractDlg->Create();
	// pExtractDlg will be deleted by itself when dialog close
}

