/***********************************************************************
 * 
 *  Copyright (C) 2005-2006 Novell, Inc.
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License as published by the Free Software Foundation; version 2.1
 *  of the License.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Library General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free
 *  Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 * 
 *  To contact Novell about this file by physical or electronic mail, 
 *  you may find current contact information at www.novell.com.
 * 
 ***********************************************************************/


namespace Novell.CASA.GUI 
{


	using System;
	using System.IO;
	using System.Diagnostics;
	using Gtk;
	using Glade;
	using Novell.CASA;
	using Novell.CASA.MiCasa.Common;
	using Novell.CASA.MiCasa.Communication;

#if W32
	using Microsoft.Win32;
#endif

	public class CasaMain
	{	
		public MiCasa 		objMiCasa 	= null; 
		public Firefox		objFirefox 	= null;
		public Mozilla 		objMozilla 	= null;
		public KdeWallet 	objKdeWallet 	= null;
		public GnomeKeyring	objGnomeKeyring = null;
	 
		public static 	        Glade.XML 	gxml;
	
		int loginPromptCount = 3;	

		#region Glade Widgets
	
		[Glade.Widget] 
		Gtk.Window 	windowMain;

		[Glade.Widget] 
		Gtk.TreeView	tvLog;
	
		[Glade.Widget]
		Gtk.Notebook	notebookStores;
	
		[Glade.Widget]
		Gtk.Dialog 	dialogPersistentStorage, 
			dialogPreferences, 
			dialogAbout, 
			dialogLogin, 
			dialogLoginContinue, 
			dialogConfirmRefresh,
			dialogSingleInstance,
			dialogLoginReprompt,
			dialogShortPassword,
			dialogResetMP,
			dialogStillRunning;
						
		[Glade.Widget] 
		Gtk.Entry	entryMasterPassword1, 
			entryMasterPassword2, 
			entryMasterPassword3, 
			entryMasterPassword4,
			entryOldMP,
			entryNewMP1,
			entryNewMP2;
						
		[Glade.Widget] 
		Gtk.CheckButton		checkbuttonFirefox, 
			checkbuttonMozilla, 
			checkbuttonGnomeKeyring, 
			checkbuttonKdeWallet,
			checkbuttonCloseMessage;
						
		[Glade.Widget] 
		Gtk.Label			label88, 
			labelLoginContinue1, 
			labelLoginContinue2;
						
		[Glade.Widget] 
		Gtk.Button	okbuttonPersistentStorage;
			
		[Glade.Widget] 
		Gtk.MenuItem 		mmiNew,
			mmiNewKey,
			mmiView, 
			mmiLink, 
			mmiCopy, 
			mmiDelete,
			mmiRefresh,
			mmiLockSecrets,
			mmiUnlockSecrets,
			mmiDestroySecrets,
			mmiEdit,
			mmiOptions,
			mmiDebug;
			
		[Glade.Widget]
					
			#endregion


		public static CasaTray mCasaTray = null;
		public static bool m_bShowDebug = false;
		public static bool m_bNotifyUser = true;
		public static bool m_bGuiLocked = false;



		///#######################################################################
		/// MAIN
	
		/// <summary>	
		/// The main entry point for the CASA application.	
		/// </summary>
		[STAThread]
		public static void Main(string[] args)
		{
			Logger.DbgLog("GUI:CasaMain.Main() - BEGIN");

			Common.ReadPlatform();
		
			Application.Init();  
		
			try 
			{
				if (Common.IsArgSet(args, Common.ARG_DEBUG))
					m_bShowDebug = true;

				// ping micasad
				Ping ping = new Ping();
				ping.clientmessage = "Hello micasad";
				MiCasaRequestReply.Send(MiCasaRequestReply.VERB_PING_MICASAD,ping);
			
				new CasaMain(args);															
				Application.Run();
			
			}
			catch (Exception e)
			{		
				string message = "miCASA services are not available";
				//Console.WriteLine("CasaMain: EXCEPTION= "+e.ToString());
				if (m_bShowDebug)
					message = e.ToString();

				MessageDialog md=new MessageDialog(null,Gtk.DialogFlags.Modal,
					Gtk.MessageType.Error,
					Gtk.ButtonsType.Close,
					message);

				md.Response+=new ResponseHandler(md_ResponseCloseWindow);
				md.SetPosition(Gtk.WindowPosition.CenterAlways);
				md.Show();
				Application.Run();			  
			}
		
		      
			Logger.DbgLog("GUI:CasaMain.Main() - END");
		}

	
	

		///#######################################################################
		/// CONSTRUCTOR
	
		/// <summary>
		/// CasaMain constructor funtion.
		/// </summary>
		public CasaMain(string[] args) 
		{
			Logger.DbgLog("GUI:CasaMain.CasaMain() - BEGIN");
				
			if( false == Common.CheckForSingleInstance() )
			{	      		
				MasterPasswordAuthentication();                       		

			
				if (Common.IsTrayAvailable()) // && Common.IsArgSet(args, Common.ARG_SHOW_TRAY_ICON))
				{
					try 
					{
						if (mCasaTray == null)
							mCasaTray = new CasaTray(this);
					}
					catch{}
				}
						
			}
			else
			{			
				//if (Common.IS_LINUX)
				{
					Glade.XML gxmlTemp = new Glade.XML(Common.GladeFile, "dialogSingleInstance", null);
					gxmlTemp.Autoconnect(this);					
				}
				//else
				//{	
				//	Common.FocusExistingApp();
				//}
			}		
		
			Logger.DbgLog("GUI:CasaMain.CasaMain() - END");          
		}
    
    
        
		///#######################################################################
		/// INITIALIZE MAIN GUI
    
		/// <summary>
		/// Main GUI initializing routine. This routine builds the Main window of CASA.
		/// </summary>
		public void InitializeGUI()
		{
			Logger.DbgLog("GUI:CasaMain.InitializeGUI() - BEGIN");
    	    	    	    	    	
			gxml = new Glade.XML(Common.GladeFile, "windowMain", null);
			gxml.Autoconnect(this);

			if (!m_bShowDebug)
				mmiDebug.Hide();


			windowMain.DeleteEvent += new DeleteEventHandler(OnWindowMainDeleted);   
        
			/// PLATFORM SPECIFIC GUI CHANGES
			//ConfigureGUI();
		
			/// POLICY INIT
			StorePolicyInterface.Init();
        
			Logger.DbgLog("GUI:CasaMain.InitializeGUI() - miCASA policy = " + Common.IS_MICASA);
			Logger.DbgLog("GUI:CasaMain.InitializeGUI() - Firefox policy = " + Common.IS_FIREFOX);
			Logger.DbgLog("GUI:CasaMain.InitializeGUI() - Mozilla policy = " + Common.IS_MOZILLA);
			Logger.DbgLog("GUI:CasaMain.InitializeGUI() - KdeWallet policy = " + Common.IS_KDEWALLET);
			Logger.DbgLog("GUI:CasaMain.InitializeGUI() - GNOME Keyring policy = " + Common.IS_GNOMEKEYRING);
        
			/// STOREDATA INIT
			StoreDataInterface.Init();
        
			if( Common.IS_MICASA )
			{
				Logger.DbgLog("GUI:CasaMain.new MiCasa().");    	
				objMiCasa = new MiCasa();
			}
			else
				(notebookStores.GetNthPage(Common.STORE_MICASA)).Visible = Common.IS_MICASA;	      
                          
			if( Common.IS_FIREFOX )
			{
				Logger.DbgLog("GUI:CasaMain.new Firefox().");
				objFirefox = new Firefox();
			}
			else
				(notebookStores.GetNthPage(Common.STORE_FIREFOX)).Visible = Common.IS_FIREFOX;	      
        
			if( Common.IS_MOZILLA )
			{
				Logger.DbgLog("GUI:CasaMain.new Mozilla().");
				objMozilla = new Mozilla();
			}
			else
				(notebookStores.GetNthPage(Common.STORE_MOZILLA)).Visible = Common.IS_MOZILLA;	      
        
			if( Common.IS_KDEWALLET )
			{
				Logger.DbgLog("GUI:CasaMain.new KdeWallet().");        	
				objKdeWallet = new KdeWallet();
			}
			else
				(notebookStores.GetNthPage(Common.STORE_KDEWALLET)).Visible = Common.IS_KDEWALLET;	      
        
			if( Common.IS_GNOMEKEYRING )
			{
				Logger.DbgLog("GUI:CasaMain.new GnomeKeyring().");        	
				objGnomeKeyring = new GnomeKeyring();
			}
			else
				(notebookStores.GetNthPage(Common.STORE_GNOMEKEYRING)).Visible = Common.IS_GNOMEKEYRING;	      
        
			notebookStores.CurrentPage = Common.STORE_MICASA;

			if (MiCASAStore.IsLocked())
				LockGUI();
			else
				UnlockGUI();
		
			windowMain.Show();
                
			Logger.DbgLog("GUI:CasaMain.InitializeGUI() - END");
		}
    
    
    
		///#######################################################################
		/// MASTER PASSWORD AUTHENTICATION
    
		/// <summary>
		/// This routine implements the MasterPassword authentication.
		/// </summary>
		public void MasterPasswordAuthentication()
		{  
			Logger.DbgLog("GUI:CasaMain.Login() - BEGIN");
                	    	    	
			if( true == IsMasterPasswordSet() )
			{    		
				Logger.DbgLog("GUI:CasaMain.Login() - IsMasterPasswordSet returned true");
    	        		
				if( false == miCASA.IsSecretPersistent(1,"") )
				{    		    
					Logger.DbgLog("GUI:CasaMain.Login() - IsMasterPasswordSet returned false");    		    
					Glade.XML gxmlTemp = new Glade.XML (Common.GladeFile, "dialogLogin", null);
					gxmlTemp.Autoconnect (this);
					dialogLogin.TransientFor = windowMain;        
					entryMasterPassword3.Text="";
					label88.Hide();
					entryMasterPassword4.Hide();
				}
				else
				{        		
					Logger.DbgLog("GUI:CasaMain.Login() - IsMasterPasswordSet returned true");
					InitializeGUI();
				}
			} 
			else
			{        	
				Logger.DbgLog("GUI:CasaMain.Login() - IsMasterPasswordSet returned false");
        	
				Glade.XML gxmlTemp = new Glade.XML(Common.GladeFile, "dialogLogin", null);
				gxmlTemp.Autoconnect(this);        
				entryMasterPassword3.Text="";
				entryMasterPassword4.Text="";
			} 	          	        
    
			Logger.DbgLog("GUI:CasaMain.Login() - END");
		}
    
    
    
		public void okbuttonLogin_clicked(object abj, EventArgs args)
		{    
			Logger.DbgLog("GUI:CasaMain.okbuttonLogin_clicked() - BEGIN");
                
			if( true == entryMasterPassword4.Visible )
			{
				if( entryMasterPassword3.Text.Length < 8 )
				{
					Glade.XML gxmlTemp = new Glade.XML (Common.GladeFile, "dialogShortPassword", null);
					gxmlTemp.Autoconnect (this);	
		
				}
				else if(entryMasterPassword3.Text != "" && (entryMasterPassword3.Text == entryMasterPassword4.Text) && entryMasterPassword3.Text.Length >= 8)
				{ 
					miCASA.SetMasterPassword(0, entryMasterPassword3.Text);
					MiCasaRequestReply.Send(MiCasaRequestReply.VERB_UNLOCK_STORE, entryMasterPassword3.Text);
					dialogLogin.Destroy();        						
					InitializeGUI();		
				}
				else
				{
					entryMasterPassword3.Text="";
					entryMasterPassword4.Text="";
					entryMasterPassword3.HasFocus=true;
				}
			}
			else
			{
				if( 0 == miCASA.SetMasterPassword(0, entryMasterPassword3.Text) )
				{
					MiCasaRequestReply.Send(MiCasaRequestReply.VERB_UNLOCK_STORE, entryMasterPassword3.Text);
					dialogLogin.Destroy();        						
					InitializeGUI();				
				}
				else
				{				
					Logger.DbgLog("GUI:CasaMain.okbuttonLogin_clicked() - MasterPassword verification failed.");
					//dialogLogin.Destroy();				
					//LoginContinue("<b>Master Password verfication failed</b>", "The store will not be persistent");				
					loginPromptCount--;
					dialogLogin.Hide();
							
					if( loginPromptCount > 0 ) 
					{
						dialogLogin.Show();
						entryMasterPassword3.Text="";
					}
					else
					{					
						Glade.XML gxmlTemp = new Glade.XML (Common.GladeFile, "dialogLoginReprompt", null);
						gxmlTemp.Autoconnect (this);					
					}									
				}
			}
				
			Logger.DbgLog("GUI:CasaMain.okbuttonLogin_clicked() - END");          	   	
		}

		public void on_helpbuttonAuthentication_clicked(object obj, EventArgs args)
		{
			Common.ShowHelpUrl("CASAMasterPasswordAuthentication.htm");	
		}
    
		internal void on_buttonRetryRepropmt_clicked(object obj, EventArgs args)
		{
			dialogLoginReprompt.Destroy();
			dialogLogin.Show();
			entryMasterPassword3.Text="";
			loginPromptCount = 3;
		}
	
		internal void on_buttonRetryShortPassword_clicked(object obj, EventArgs args)
		{
			dialogShortPassword.Destroy();
			entryMasterPassword3.Text = "";
			entryMasterPassword4.Text = "";
			entryMasterPassword3.HasFocus = true;
		}
	
		internal void on_buttonCloseReprompt_clicked(object obj, EventArgs args)
		{
			dialogLoginReprompt.Destroy();
			dialogLogin.Destroy();
			HandleQuit();		
		}
    
		public void closebuttonLogin_clicked(object abj, EventArgs args)
		{
			dialogLogin.Destroy();  
			HandleQuit();    	
		}
    
    
		public void OnDialogLoginDeleted(object obj, DeleteEventArgs args) 
		{
			Logger.DbgLog("GUI:CasaMain.OnDialogLoginDeleted() - BEGIN");
    	
			HandleQuit();    	
			args.RetVal = true;
        
			Logger.DbgLog("GUI:CasaMain.OnDialogLoginDeleted() - END");
		}
    
		public void on_entryMasterPassword3_activate(object obj, EventArgs args)
		{
			if( true == entryMasterPassword4.Visible )
				entryMasterPassword4.HasFocus = true;
			else if( "" != entryMasterPassword3.Text )
				okbuttonLogin_clicked(obj, args);
		}
    
		public void on_entryMasterPassword4_activate(object obj, EventArgs args)
		{
			okbuttonLogin_clicked(obj, args);
		}
    
		public bool IsMasterPasswordSet()
		{
			Logger.DbgLog("GUI:CasaMain.IsMasterPasswordSet() - BEGIN");
    	
			string MICASA_PASSCODE_BY_MASTER_PASSWD_FILE = "/.miCASAPCByMPasswd";
			string fileName = GetUserHomeDir() + MICASA_PASSCODE_BY_MASTER_PASSWD_FILE;
           	
			Logger.DbgLog("GUI:CasaMain.IsMasterPasswordSet() - END");
			return (File.Exists(fileName));
		}
    
		private string GetUserHomeDir()
		{
			if (Common.IS_LINUX)	
				return Environment.GetEnvironmentVariable("HOME");
			else
				return Environment.GetEnvironmentVariable("USERPROFILE");
		
		}
    
		///#######################################################################
		/// LOGIN WARNING DIALOG
    
		/// <summary>
		/// Error dialog prompt for MasterPassword authentication
		/// </summary>
		public void LoginContinue(string LabelMain, string LabelTips)
		{
			Logger.DbgLog("GUI:CasaMain.LoginContinue() - BEGIN");
    	
			Glade.XML gxmlTemp = new Glade.XML(Common.GladeFile, "dialogLoginContinue", null);
			gxmlTemp.Autoconnect(this);
			dialogLoginContinue.TransientFor = windowMain;    	    	
			labelLoginContinue1.LabelProp = LabelMain;
			labelLoginContinue2.LabelProp = LabelTips;
    	
			Logger.DbgLog("GUI:CasaMain.LoginContinue() - END");    	
		}
    
		public void on_buttonLoginContinue_clicked(object abj, EventArgs args)
		{
			dialogLoginContinue.Destroy();
			InitializeGUI();
		}
    
       
		///#######################################################################
		/// ON MAIN MENU ACTIVATED HANDLERS
    
	
	
		internal void on_notebookStores_switch_page(object obj, SwitchPageArgs args)
		{
			switch(args.PageNum)
			{    		    		
				case Common.STORE_MICASA: 				 
					break;
    										
				case Common.STORE_FIREFOX:	
					break;
    				
				case Common.STORE_MOZILLA:	
					break;
    		
				case Common.STORE_KDEWALLET:
					if( false == objKdeWallet.IS_STORE_AGGREGATED )
					{
						objKdeWallet.AggregateStore();
						objKdeWallet.IS_STORE_AGGREGATED = true;
					}
					break;
    				
				case Common.STORE_GNOMEKEYRING: 
					if( false == objGnomeKeyring.IS_STORE_AGGREGATED )
					{
						objGnomeKeyring.AggregateStore();
						objGnomeKeyring.IS_STORE_AGGREGATED = true;			
					}
					break;
			}		
	
		}
	
	
		/// <summary>
		///
		/// </summary>
		internal void FileMenuActivated(object obj, EventArgs args)
		{
			Logger.DbgLog("GUI:CasaMain.FileMenuActivated() - BEGIN");
    	
			if (MiCASAStore.IsLocked())
			{
				LockGUI();
				Logger.DbgLog("GUI:CasaMain.FileMenuActivated() Store is locked - END");	
				return;
			}
			else
			{
				if (m_bGuiLocked)
					UnlockGUI();
			}


			switch(notebookStores.CurrentPage)
			{    		    		
				case Common.STORE_MICASA: 
					if( 0 != objMiCasa.tvSecretIDMiCasa.Selection.CountSelectedRows() )
					{
						mmiNew.Sensitive = mmiNewKey.Sensitive = true;
					}
					else
					{						
						mmiNewKey.Sensitive = false;						
					}
					break;
    										
				case Common.STORE_FIREFOX:	
					break;
    				
				case Common.STORE_MOZILLA:	
					break;
    		
				case Common.STORE_KDEWALLET:
					if( 0 != objKdeWallet.tvSecretIDKdeWallet.Selection.CountSelectedRows() )
					{
						mmiNew.Sensitive = mmiNewKey.Sensitive = true;
					}
					else
					{
						mmiNewKey.Sensitive = false;
					}
					break;
    				
				case Common.STORE_GNOMEKEYRING: 
					if( 0 != objGnomeKeyring.tvSecretIDGnomeKeyring.Selection.CountSelectedRows() )
					{
						mmiNew.Sensitive = mmiNewKey.Sensitive = true;						
					}
					else
					{
						mmiNewKey.Sensitive = false;
					}
					break;
			}
    	
			Logger.DbgLog("GUI:CasaMain.FileMenuActivated() - END");	
		}
    
    
    
		/// <summary>
		///
		/// </summary>
		internal void EditMenuActivated(object obj, EventArgs args)
		{
			Logger.DbgLog("GUI:CasaMain.EditMenuActivated() - BEGIN");
    	
			switch(notebookStores.CurrentPage)
			{    		
				case Common.STORE_MICASA: 
					if( 0 != objMiCasa.tvSecretIDMiCasa.Selection.CountSelectedRows() )
					{
						mmiView.Sensitive = mmiLink.Sensitive = mmiDelete.Sensitive = true;
						mmiCopy.Sensitive = false; 
					}
					else
					{
						mmiView.Sensitive = mmiLink.Sensitive = mmiCopy.Sensitive = mmiDelete.Sensitive = false;
					}
					break;
    										
				case Common.STORE_FIREFOX:	
					break;
    				
				case Common.STORE_MOZILLA:	
					break;
    		
				case Common.STORE_KDEWALLET:
					if( 0 != objKdeWallet.tvSecretIDKdeWallet.Selection.CountSelectedRows() )
					{
						mmiView.Sensitive = mmiDelete.Sensitive = true;
						mmiLink.Sensitive = mmiCopy.Sensitive = false; 
					}
					else
					{
						mmiView.Sensitive = mmiLink.Sensitive = mmiCopy.Sensitive = mmiDelete.Sensitive = false;
					}
					break;
    				
				case Common.STORE_GNOMEKEYRING: 
					if( 0 != objGnomeKeyring.tvSecretIDGnomeKeyring.Selection.CountSelectedRows() )
					{
						mmiView.Sensitive = mmiDelete.Sensitive = true;
						mmiLink.Sensitive = mmiCopy.Sensitive = false; 
					}
					else
					{
						mmiView.Sensitive = mmiLink.Sensitive = mmiCopy.Sensitive = mmiDelete.Sensitive = false;
					}
					break;
			}
    	
			Logger.DbgLog("GUI:CasaMain.EditMenuActivated() - END");
		}
    
    
		///#######################################################################
		/// REFRESH ALL STORES
    
		/// <summary>
		///
		/// </summary>
		public void RefreshAllStores(object obj, EventArgs args)
		{
			Glade.XML gxmlTemp = new Glade.XML (Common.GladeFile, "dialogConfirmRefresh", null);
			gxmlTemp.Autoconnect (this);
			dialogConfirmRefresh.TransientFor = windowMain;  	        
		}
    
		public void on_buttonRefreshYes_clicked(object abj, EventArgs args)
		{
			Logger.DbgLog("GUI:CasaMain.on_buttonRefreshYes_clicked() - BEGIN");
    	
			RefreshStores();
    	
			dialogConfirmRefresh.Destroy();
    	
			Logger.DbgLog("GUI:CasaMain.on_buttonRefreshYes_clicked() - END");
		}
    
		public void on_buttonRefreshNo_clicked(object abj, EventArgs args)
		{
			dialogConfirmRefresh.Destroy();
		}

		public void on_helpbuttonRefresh_clicked(object obj, EventArgs Args)
		{
			Common.ShowHelpUrl("RefreshStore.htm");
		}
        
    
		///#######################################################################
		/// QUIT APPLICATION
    
		/// <summary>
		///
		/// </summary>
		public void QuitApplication(object obj, EventArgs args)
		{
			Logger.DbgLog("GUI:CasaMain.QuitApplication() - BEGIN");
    	
			//windowMain.Destroy();
			HandleQuit();    	
    	
			Logger.DbgLog("GUI:CasaMain.QuitApplication() - END");    	        
		}
    
    
    
		///#######################################################################
		/// ADD NEW SECRET
    
		/// <summary>
		///
		/// </summary>
		public void OnNewSecretActivated(object obj, EventArgs args)
		{   
			Logger.DbgLog("GUI:CasaMain.NewSecret() - BEGIN");
    	 	
			switch(notebookStores.CurrentPage)
			{    		
				case Common.STORE_MICASA:
					objMiCasa.OnNewSecretActivated(obj, args);    				
					break;
    										
				case Common.STORE_FIREFOX:
					break;
    		
				case Common.STORE_MOZILLA:
					break;
    		
				case Common.STORE_KDEWALLET:
					objKdeWallet.OnNewSecretActivated(obj, args);
					break;
    		
				case Common.STORE_GNOMEKEYRING: 
					objGnomeKeyring.OnNewSecretActivated(obj, args);
					break;
			}  	
    	
			Logger.DbgLog("GUI:CasaMain.NewSecret() - END");          	        
		}
    
    
    
		///#######################################################################
		/// ADD NEW KEY
    
		/// <summary>
		///
		/// </summary>
		public void OnNewKeyActivated(object obj, EventArgs args)
		{
			Logger.DbgLog("GUI:CasaMain.NewKeyValue() - BEGIN");
    	
			switch(notebookStores.CurrentPage)
			{
				case Common.STORE_MICASA:
					objMiCasa.OnNewKeyActivated(obj, args);    				
					break;
    										
				case Common.STORE_FIREFOX:
					break;
    		
				case Common.STORE_MOZILLA:
					break;
    		
				case Common.STORE_KDEWALLET:
					objKdeWallet.OnNewKeyActivated(obj, args);
					break;
    		
				case Common.STORE_GNOMEKEYRING:
					objGnomeKeyring.OnNewKeyActivated(obj, args);
					break;
			} 
    	
			Logger.DbgLog("GUI:CasaMain.NewKeyValue() - END");
		}
	   

		///#######################################################################
		/// UI handling

		public void OnLockMiCASASecrets(object sender, EventArgs args)
		{
			Logger.DbgLog("GUI:CasaMain.OnLockMiCASASecrets() - START");
			MiCasaRequestReply.Send(MiCasaRequestReply.VERB_LOCK_STORE);
			LockGUI();
			if (mCasaTray != null)
				mCasaTray.UpdateTrayIcon(true);
			RefreshStores();
			Logger.DbgLog("GUI:CasaMain.OnLockMiCASASecrets() - END");
		}

		public void OnUnLockMiCASASecrets(object sender, EventArgs args)
		{
			Logger.DbgLog("GUI:CasaMain.OnUnLockMiCASASecrets() - START");
			CommonGUI cg = new CommonGUI();
			cg.HandleUnlock(this, mCasaTray);
			Logger.DbgLog("GUI:CasaMain.OnUnLockMiCASASecrets() - END");
		}

		public void OnDestroyMiCASASecrets(object sender, EventArgs args)
		{
			Logger.DbgLog("GUI:CasaMain.OnDestroyMiCASASecrets() - START");	
			CommonGUI temp = new CommonGUI();
			temp.menuDestroyMiCasa_Activated(this, mCasaTray);		
			Logger.DbgLog("GUI:CasaMain.OnDestroyMiCASASecrets() - END");
		}


		internal void LockGUI()
		{
			mmiLockSecrets.Sensitive = false;
			mmiUnlockSecrets.Sensitive = true;
			mmiDestroySecrets.Sensitive = false;
			notebookStores.Sensitive = false;
			
			mmiNew.Sensitive = false;
			mmiRefresh.Sensitive = false;
			mmiDebug.Sensitive = false;
			mmiOptions.Sensitive = false;
			mmiEdit.Sensitive = false;
			m_bGuiLocked = true;						
		}

		internal void UnlockGUI()
		{
			mmiLockSecrets.Sensitive = true;
			mmiUnlockSecrets.Sensitive = false;
			mmiDestroySecrets.Sensitive = true;
			notebookStores.Sensitive = true;					
				
			mmiNew.Sensitive = true;
			mmiRefresh.Sensitive = true;
			mmiDebug.Sensitive = true;
			mmiOptions.Sensitive = true;
			mmiEdit.Sensitive = true;

			m_bGuiLocked = false;

			//refresh secrets
			RefreshStores();
			
		}
    

		///#######################################################################
		/// VIEW KEY-VALUES
    
		/// <summary>
		/// VIEW Key-Values
		/// </summary>
		public void ViewKeyValue(object obj, EventArgs args)
		{
			Logger.DbgLog("GUI:CasaMain.ViewKeyValue() - BEGIN");
    	
			switch(notebookStores.CurrentPage)
			{
				case Common.STORE_MICASA:
					objMiCasa.ViewKeyValues();    				
					break;
    										
				case Common.STORE_FIREFOX:
					//objFirefox.ViewKeyValues();
					break;
    		
				case Common.STORE_MOZILLA:
					//objMozilla.ViewKeyValues();
					break;
    		
				case Common.STORE_KDEWALLET:
					objKdeWallet.ViewKeyValues();
					break;
    		
				case Common.STORE_GNOMEKEYRING:
					objGnomeKeyring.ViewKeyValues();
					break;
			}
    	
			Logger.DbgLog("GUI:CasaMain.ViewKeyValue() - END");      	        
		}
    
    
    
		///#######################################################################
		/// LINK KEY-VALUE
    
		/// <summary>
		/// LINK Key-Values
		/// </summary>
		public void LinkKeyValue(object obj, EventArgs args)
		{
			Logger.DbgLog("GUI:CasaMain.LinkKeyValue() - BEGIN");
    	
			switch(notebookStores.CurrentPage)
			{
				case Common.STORE_MICASA:
					objMiCasa.ViewKeyValues();    				
					break;
    										
				case Common.STORE_FIREFOX:
					break;
    		
				case Common.STORE_MOZILLA:
					break;
    		
				case Common.STORE_KDEWALLET:
					break;
    		
				case Common.STORE_GNOMEKEYRING:
					break;
			}      
        
			Logger.DbgLog("GUI:CasaMain.LinkKeyValue() - END");  	          	          	          	        
		}
    
    
    
		///#######################################################################
		/// COPY KEY-VALUE
    
		/// <summary>
		/// COPY Key-Values
		/// </summary>
		public void CopyKeyValue(object obj, EventArgs args)
		{
			Logger.DbgLog("GUI:CasaMain.CopyKeyValue() - BEGIN");
    	
			//Glade.XML gxmlTemp = new Glade.XML (Common.GladeFile, "dialogCopyKeyValue", null);
			//gxmlTemp.Autoconnect (this);        
        
			Logger.DbgLog("GUI:CasaMain.CopyKeyValue() - END");  	          	          	          	        
		}
    
    
    
		///#######################################################################
		/// DELETE SECRET
    
		/// <summary>
		/// DELETE Secret
		/// </summary>
		public void DeleteSecret(object obj, EventArgs args)
		{
			Logger.DbgLog("GUI:CasaMain.DeleteSecret() - BEGIN");
    	
			switch(notebookStores.CurrentPage)
			{
				case Common.STORE_MICASA:
					objMiCasa.OnDeleteActivated(obj, args);    				
					break;
    										
				case Common.STORE_FIREFOX:
					break;
    		
				case Common.STORE_MOZILLA:
					break;
    		
				case Common.STORE_KDEWALLET:
					objKdeWallet.OnDeleteActivated(obj, args);
					break;
    		
				case Common.STORE_GNOMEKEYRING:
					objGnomeKeyring.OnDeleteActivated(obj, args);
					break;			
			}   
        
			Logger.DbgLog("GUI:CasaMain.DeleteSecret() - END");          	          	          	          	        
		}
    

		///#######################################################################
		/// Reset Master Password CALLED VIA MAIN MENU
    
		/// <summary>
		/// 
		/// </summary>
		public void ResetMasterPassword(object obj, EventArgs args)
		{    	    	
			Logger.DbgLog("GUI:CasaMain.ResetMasterPassword() - BEGIN");
    	
			Glade.XML gxmlTemp = new Glade.XML (Common.GladeFile, "dialogResetMP", null);
			gxmlTemp.Autoconnect (this);
			dialogResetMP.TransientFor = windowMain;
			entryOldMP.Text="";
			entryNewMP1.Text="";
			entryNewMP2.Text="";			        
			Logger.DbgLog("GUI:CasaMain.ResetMasterPassword() - END");          	          	          	          	        
		}    
    
		public void okbuttonResetMasterPWD_clicked(object abj, EventArgs args)
		{
			Logger.DbgLog("GUI:CasaMain.okbuttonResetMasterPWD_clicked() - BEGIN");
    	
			if (entryOldMP.Text == "")
			{
				DisplayError("You must enter you current Master Password");
				return;
			}

			// check Current MP
			if (entryOldMP.Text != "")
			{
				int rcode = miCASA.SetMasterPassword(1, entryOldMP.Text);
				if (rcode != 0)
				{
					DisplayError("Current Master Password is not correct");
					return;
				}
			}

			if (entryNewMP1.Text.Length < 8)
			{
				Glade.XML gxmlTemp = new Glade.XML (Common.GladeFile, "dialogShortPassword", null);
				gxmlTemp.Autoconnect (this);
				return;
			}

			if (entryNewMP1.Text != entryNewMP2.Text)
			{
				DisplayError("New Master Passwords do not match");
				return;
			}
		
			if (miCASA.ChangeMasterPassword(entryOldMP.Text, entryNewMP1.Text))
				dialogResetMP.Destroy();
			else
				DisplayError("Change failed");
		    	
			Logger.DbgLog("GUI:CasaMain.okbuttonResetMasterPWD_clicked() - END");
		}
    
		public void cancelbuttonResetMasterPWD_clicked(object abj, EventArgs args)
		{
			dialogResetMP.Destroy();
		}	

		public void on_helpbuttonResetMP_clicked(object obj, EventArgs args)
		{
			Common.ShowHelpUrl("CASAMasterPasswordAuthentication.htm");
		}

		private void DisplayError(String sErrorMessage)
		{
			MessageDialog md = new MessageDialog(windowMain,
				Gtk.DialogFlags.Modal,
				Gtk.MessageType.Warning,
				Gtk.ButtonsType.Close,
				sErrorMessage);

			md.Response +=new ResponseHandler(md_Response);
			//md_ResponseCloseWindow
			md.Show();

		}

          
    
		///#######################################################################
		/// PERSISTENT STORAGE CALLED VIA MAIN MENU
    
		/// <summary>
		/// 
		/// </summary>
		public void PersistentStorage(object obj, EventArgs args)
		{    	    	
			Logger.DbgLog("GUI:CasaMain.PersistentStorage() - BEGIN");
    	
			Glade.XML gxmlTemp = new Glade.XML (Common.GladeFile, "dialogPersistentStorage", null);
			gxmlTemp.Autoconnect (this);
			dialogPersistentStorage.TransientFor = windowMain;
			entryMasterPassword1.Text="";
			entryMasterPassword2.Text="";
			
			if(IsMasterPasswordSet() == true)
			{        
				entryMasterPassword1.Sensitive=false;
				entryMasterPassword2.Sensitive=false;
				okbuttonPersistentStorage.Sensitive=false;
			}
        
			Logger.DbgLog("GUI:CasaMain.PersistentStorage() - END");          	          	          	          	        
		}    
    
		public void okbuttonPersistentStorage_clicked(object abj, EventArgs args)
		{
			Logger.DbgLog("GUI:CasaMain.okbuttonPersistentStorage_clicked() - BEGIN");
    	
			if((entryMasterPassword1.Text != "" && entryMasterPassword2.Text != "") && (entryMasterPassword1.Text == entryMasterPassword2.Text))
			{    		
				//StorePolicyInterface.SetMasterPassword(entryMasterPassword1.Text);
				miCASA.SetMasterPassword(0, entryMasterPassword1.Text);
				dialogPersistentStorage.Destroy();
			}
      	
			Logger.DbgLog("GUI:CasaMain.okbuttonPersistentStorage_clicked() - END");
		}
    
		public void cancelbuttonPersistentStorage_clicked(object abj, EventArgs args)
		{
			dialogPersistentStorage.Destroy();
		}
    
    
    
		///#######################################################################
		/// PREFERENCES
    
		/// <summary>
		/// 
		/// </summary>
		public void Preferences(object obj, EventArgs args)
		{
			Logger.DbgLog("GUI:CasaMain.Preferences() - BEGIN");
    	
			Glade.XML gxmlTemp = new Glade.XML (Common.GladeFile, "dialogPreferences", null);
			gxmlTemp.Autoconnect (this);
			dialogPreferences.SetPosition(Gtk.WindowPosition.CenterOnParent);
			dialogPreferences.TransientFor = windowMain;		
			checkbuttonFirefox.Active=Common.IS_FIREFOX;
			checkbuttonMozilla.Active=Common.IS_MOZILLA;
			checkbuttonGnomeKeyring.Active=Common.IS_GNOMEKEYRING;
			checkbuttonKdeWallet.Active=Common.IS_KDEWALLET;

			if (Common.IS_WINDOWS)
			{
				checkbuttonGnomeKeyring.Sensitive = false;
				checkbuttonKdeWallet.Sensitive = false;
			}
        
			Logger.DbgLog("GUI:CasaMain.Preferences() - END");  	          	        
		}
    
		public void okbuttonPreferences_clicked(object abj, EventArgs args)
		{    	
			Logger.DbgLog("GUI:CasaMain.okbuttonPreferences_clicked() - BEGIN");
        
			string[] storeID = new string[]{""};
        
			notebookStores.GetNthPage(Common.STORE_FIREFOX).Visible		 = Common.IS_FIREFOX	  = checkbuttonFirefox.Active;  	   	
			notebookStores.GetNthPage(Common.STORE_MOZILLA).Visible		 = Common.IS_MOZILLA	  = checkbuttonMozilla.Active;
			notebookStores.GetNthPage(Common.STORE_GNOMEKEYRING).Visible = Common.IS_GNOMEKEYRING = checkbuttonGnomeKeyring.Active;
			notebookStores.GetNthPage(Common.STORE_KDEWALLET).Visible	 = Common.IS_KDEWALLET	  = checkbuttonKdeWallet.Active;
		
			StorePolicyInterface.SetAggregationPolicy(Common.STORE_FIREFOX, Common.IS_FIREFOX, storeID, 1);
			StorePolicyInterface.SetAggregationPolicy(Common.STORE_MOZILLA, Common.IS_MOZILLA, storeID, 1);
			StorePolicyInterface.SetAggregationPolicy(Common.STORE_KDEWALLET, Common.IS_KDEWALLET, storeID, 1);
			StorePolicyInterface.SetAggregationPolicy(Common.STORE_GNOMEKEYRING, Common.IS_GNOMEKEYRING, storeID, 1);
		
			StorePolicyInterface.SaveAggregationPolicy();
		
						
			if(Common.IS_FIREFOX)
			{
				if( null == objFirefox )
					objFirefox = new Firefox();
				
				objFirefox.AggregateStore();
			}
			if(Common.IS_MOZILLA)
			{
				if( null == objMozilla )
					objMozilla = new Mozilla();
			
				objMozilla.AggregateStore();
			}
			if(Common.IS_KDEWALLET)
			{
				if( null == objKdeWallet )
					objKdeWallet = new KdeWallet();
			
				objKdeWallet.AggregateStore();
			}
			if(Common.IS_GNOMEKEYRING)
			{
				if( null == objGnomeKeyring )
					objGnomeKeyring = new GnomeKeyring();
			
				objGnomeKeyring.AggregateStore();
			}
		
		
			dialogPreferences.Destroy();
		
			Logger.DbgLog("GUI:CasaMain.okbuttonPreferences_clicked() - END");          	   	
		}
    
		public void cancelbuttonPreferences_clicked(object abj, EventArgs args)
		{
			dialogPreferences.Destroy();
		}
    

		public void on_helpbuttonPreferences_clicked(object obj, EventArgs args)
		{
			Common.ShowHelpUrl("Preferences.htm");
		}


		/*
		private bool IsTraySetForStartup()
		{
#if W32
			string sStartup = CommonGUI.ReadRegKey(
				Registry.CurrentUser,
				"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run",
				"CASA Tray");
			
			if (sStartup == null || sStartup.Length < 1)
				return false;
			else 
				return true;
#endif

#if LINUX
		// TODO check startup script for the user.
		return true;
#endif
		}
		*/


		private static void md_ResponseCloseWindow(object o, ResponseArgs args)
		{		
			MessageDialog md = (MessageDialog)o;
			if (md != null)
			{
				md.Destroy();
				Application.Quit();
			}
		}
		

		internal void PromptUserForStartup()
		{
			// prompt user 						
			MessageDialog md=new MessageDialog(null,Gtk.DialogFlags.Modal,
				Gtk.MessageType.Question,
				Gtk.ButtonsType.YesNo,
				"Show the Tray Icon at startup?");

			md.SetPosition(Gtk.WindowPosition.Center);
			md.Response +=new ResponseHandler(md_Response);
			md.Modal = true;
			md.SetIconFromFile(Common.CASAICONS);
			md.Show();
		}

		private void md_Response(object o, ResponseArgs args)
		{
			if (args.ResponseId.Equals(Gtk.ResponseType.Yes))
			{

#if W32
				// get our program path
				String sPath = "\"" +Environment.GetEnvironmentVariable("ProgramFiles")+
					"\\Novell\\CASA\\bin\\CASAManager.exe\" -tray";
			
				CommonGUI.WriteRegKey(Registry.CurrentUser,
					"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run",
					"CASA Tray",
					sPath);			
#endif
			
				// TODO:  Set startup script for the user
			}

			MessageDialog md = (MessageDialog)o;
			if (md != null)
			{
				md.Destroy();			
			}
		}
    
		///#######################################################################
		/// DEBUG
    
		/// <summary>
		/// 
		/// </summary>
		public void on_create_sample_secrets1_activate(object obj, EventArgs arg)
		{
			MiCasaRequestReply.Send(MiCasaRequestReply.VERB_CREATE_TEST_SECRETS, null, null, null, null);
			//StoreDataInterface.RefreshAllStores();				    	
			objMiCasa.AggregateStore();
		}

		public void on_remove_test_secrets1_activate(object obj, EventArgs args)
		{
			MiCasaRequestReply.Send(MiCasaRequestReply.VERB_REMOVE_TEST_SECRETS, null, null, null, null);
			//StoreDataInterface.RefreshAllStores();				    	
			objMiCasa.AggregateStore();
		}
    
		///#######################################################################
		/// ABOUT
    
		/// <summary>
		/// 
		/// </summary>
		public void About(object obj, EventArgs args)
		{
			Logger.DbgLog("GUI:CasaMain.About() - BEGIN");
    	
			Glade.XML gxmlTemp = new Glade.XML (Common.GladeFile, "dialogAbout", null);
			gxmlTemp.Autoconnect (this);
			dialogAbout.TransientFor = windowMain;        	
			Logger.DbgLog("GUI:CasaMain.About() - END");
		}
    
		public void closebuttonAbout_clicked(object obj, EventArgs args)
		{
			dialogAbout.Destroy();
		}
    

		public void on_buttonNovell_clicked(object obj, EventArgs args)
		{
			Common.ShowUrl("http://www.novell.com");
		}
	
		///#######################################################################
		/// SINGLE INSTANCE DIALOG CLOSE HANDLER
    
		/// <summary>
		/// dislogSingleInstance delete window handler
		/// </summary>
		public void on_dialogSingleInstance_delete_event(object obj, DeleteEventArgs args)
		{
			dialogSingleInstance.Destroy();	
			HandleQuit();
			//Application.Quit();		
		}
	
		public void on_buttonSIClose_clicked(object obj, EventArgs args)
		{
			dialogSingleInstance.Destroy();	
			HandleQuit();
			//Application.Quit();		
		}
    
		///#######################################################################
		/// WINDOW MAIN CLOSE HANDLER
    
		/// <summary>
		/// MainWindow delete window handler
		/// </summary>
		public void OnWindowMainDeleted(object obj, DeleteEventArgs args) 
		{
			Logger.DbgLog("GUI:CasaMain.OnWindowMainDeleted() - BEGIN");
    	
			//windowMain.Destroy();
			HandleQuit();
			
			//Gtk.Application.Quit ();
			args.RetVal = true;
        
			Logger.DbgLog("GUI:CasaMain.OnWindowMainDeleted() - END");
		}  

		private void HandleQuit()
		{
			if (mCasaTray != null)
			{
				if (m_bNotifyUser)
				{
					// StillRunning(null, null);
					// prompt user 	
					
					MessageDialog md=new MessageDialog(null,Gtk.DialogFlags.Modal,
						Gtk.MessageType.Info,
						Gtk.ButtonsType.Close,
						"CASA Manager will continue to run in the task bar");

					md.SetPosition(Gtk.WindowPosition.Center);
					md.Response +=new ResponseHandler(md_Response);
					md.Modal = true;
					md.SetIconFromFile(Common.CASAICONS);
					md.Show();
				
					m_bNotifyUser = false;
					
				}

				mCasaTray.CasaManagerQuit();
				return;
			}
			else
				Application.Quit();
		}

		///#######################################################################
		/// StillRunning
    
		/// <summary>
		/// 
		/// </summary>
		public void StillRunning(object obj, EventArgs args)
		{
			Logger.DbgLog("GUI:CasaMain.StillRunning() - BEGIN");
    	
			Glade.XML gxmlTemp = new Glade.XML (Common.GladeFile, "dialogStillRunning", null);
			gxmlTemp.Autoconnect (this);
			dialogStillRunning.TransientFor = windowMain;        	
			Logger.DbgLog("GUI:CasaMain.StillRunning() - END");
		}
    
		public void btnStillRunning_clicked(object obj, EventArgs args)
		{
			if (checkbuttonCloseMessage.Active)
			{								
				m_bNotifyUser = false;
			}

			dialogStillRunning.Destroy();
		}
    

		///#######################################################################
		/// WINDOW MAIN FOCUS
		/// 
		internal void Focus()
		{
			if (windowMain != null)
				windowMain.Present();
		}

		internal void Hide()
		{
			if (windowMain != null)
				windowMain.Visible = false;
		}

		internal void Show()
		{
			if (windowMain == null)
				MasterPasswordAuthentication();
			else
			{			
				RefreshStores();
				windowMain.Visible = true;
			}
		}

		internal void Dispose()
		{	
			if (windowMain != null)
				windowMain.Destroy();
		}

		internal void RefreshStores()
		{
			if( Common.IS_MICASA )
				objMiCasa.AggregateStore();
    	
			if( Common.IS_FIREFOX )
				objFirefox.AggregateStore();
		
			if( Common.IS_MOZILLA )
				objMozilla.AggregateStore();
		
			if( Common.IS_KDEWALLET )
				objKdeWallet.AggregateStore();			
		
			if( Common.IS_GNOMEKEYRING )
				objGnomeKeyring.AggregateStore();

		}

		///#######################################################################
		/// LOGGING WINDOW operations
		/// 

		public void on_view_log_file1_activate(object obj, EventArgs args)
		{

		}

		public void on_enable_logging1_activate(object obj, EventArgs args)
		{
			Gtk.CheckMenuItem miLog = (Gtk.CheckMenuItem)obj;
			if (miLog.Active)
				OpenLogWindow();
			else
				CloseLogWindow();
		}

		internal void OpenLogWindow()
		{
			Glade.XML gxmlTemp = new Glade.XML (Common.GladeFile, "dialogLog", null);
			gxmlTemp.Autoconnect (this);		
				
			Gtk.TreeViewColumn col1 = new Gtk.TreeViewColumn("", new Gtk.CellRendererText(), "text", 0);
			tvLog.AppendColumn(col1);
			Logger.ActivateLogWindow(tvLog);
		}	

		internal void CloseLogWindow()
		{
			Logger.StopLogWindow();
			dialogLogin.Dispose();
			dialogLogin.Destroy();
		}


		///###########################################################################
		///  Help Handlers
		///###########################################################################
		public void OnMenuHelpActivate(object sender, EventArgs args)
		{
			Common.ShowHelpUrl("Contents.htm");
		}

	}

}
///###########################################################################
///				END OF FILE
///###########################################################################