# -*- coding: utf-8 -*-
import os
import wx
import wx.lib.scrolledpanel as scrolled
import _winreg
import MySQLdb
from Crypto.Cipher import AES
from Crypto.Cipher import DES3
import StringIO
import pyHook, time,sys,os,xml.dom.minidom,shutil, getopt
from time import localtime
import pythoncom
import types
import threading
import win32con
import win32process
import win32gui
import win32api
import win32evtlog
import win32api
import win32file
import win32con
import win32security # To translate NT Sids to account names.
import pyAA
import wmi
from win32com.shell import shell, shellcon
#import MySQLdb
import win32evtlogutil
#import md5
from Crypto.Hash import MD5
import codecs
import psycopg2
import webbrowser
import chardet


class MyTaskBarIcon(wx.TaskBarIcon):
    global line1,line2,line3
    def __init__(self, frame):
        global line1,line2,line3
        wx.TaskBarIcon.__init__(self)

        self.frame = frame
        self.SetIcon(wx.Icon('img/icone2.png', wx.BITMAP_TYPE_PNG), 'chronos monitor')
        self.Bind(wx.EVT_MENU, self.OnTaskBarActivate, id=1)
        self.Bind(wx.EVT_MENU, self.OnTaskBarDeactivate, id=2)
        self.Bind(wx.EVT_MENU, self.OnTaskBarClose, id=3)
        self.Bind(wx.EVT_MENU, self.OnHelp, id=4)
        self.Bind(wx.EVT_MENU, self.OnAbout, id=5)
 
    def CreatePopupMenu(self):
        menu = wx.Menu()
        menu.Append(1, 'Afficher')
        menu.Append(2, 'Cacher')
        menu.Append(3, 'Fermer')
        menu.Append(4, 'Aide')
        menu.Append(5, 'A Propos')
        return menu

    def OnAbout(self,event):
        global line1,line2,line3
        line1="Chronos Monitor Watcher"
        line2="  version beta 00.00" 
        line3="http://www.chronosmonitor.com"
        try:
            dialogframe = wx.FindWindowById(465)
            dialogframe.Close()
            WizardEnd(None, 465, 'Chronos Monitor Configuration')            
        except:
            WizardEnd(None, 465, 'Chronos Monitor Configuration')

    def OnHelp(self,event):
        def get_main_dir():
            try:
                sys.frozen
            except AttributeError:
                path = sys.argv[0]
            else:
                path = sys.executable
            return os.path.dirname(os.path.abspath(path))

        oscurdir=get_main_dir()
        path="file:///"+oscurdir+"/doc/documentationWatcher.pdf"
        webbrowser.open(path)

    def OnTaskBarClose(self, event):
##        optionsframe = wx.FindWindowById(458)
##        if optionsframe.IsShown():
##            optionsframe.Close()
##        paramframe = wx.FindWindowById(459)
##        if paramframe.IsShown():
##            paramframe.Close()
##        anaframe = wx.FindWindowById(460)
##        if anaframe.IsShown():
##            anaframe.Close()
##        dosframe = wx.FindWindowById(461)
##        if dosframe.IsShown():
##            dosframe.Close()
##        userframe = wx.FindWindowById(462)
##        if userframe.IsShown():
##            userframe.Close()
##        wizardframe = wx.FindWindowById(463)
##        if wizardframe.IsShown():
##            wizardframe.Close()

        for x in range(458,472):
            try:
                frame=wx.FindWindowById(x)
                if frame.IsShown():
                    frame.Close()
            except:
                pass
        self.frame.Close()

    def OnTaskBarActivate(self, event):
        if not self.frame.IsShown():
            self.frame.Show()
        for x in range(458,472):
            try:
                frame=wx.FindWindowById(x)
                if not frame.IsShown():
                    frame.Show()
            except:
                pass
##        optionsframe = wx.FindWindowById(458)
##        if not optionsframe.IsShown():
##            optionsframe.Show()
##        paramframe = wx.FindWindowById(459)
##        if not paramframe.IsShown():
##            paramframe.Show()
##        anaframe = wx.FindWindowById(460)
##        if not anaframe.IsShown():
##            anaframe.Show()
##        dosframe = wx.FindWindowById(461)
##        if not dosframe.IsShown():
##            dosframe.Show()
##        userframe = wx.FindWindowById(462)
##        if not userframe.IsShown():
##            userframe.Show()
##        wizardframe = wx.FindWindowById(463)
##        if not wizardframe.IsShown():
##            wizardframe.Show()


    def OnTaskBarDeactivate(self, event):
        if self.frame.IsShown():
            self.frame.Hide()
        for x in range(458,472):
            try:
                frame=wx.FindWindowById(x)
                if frame.IsShown():
                    frame.Hide()
            except:
                pass
##    optionsframe = wx.FindWindowById(458)
##    if optionsframe.IsShown():
##        optionsframe.Hide()
##    paramframe = wx.FindWindowById(459)
##    if paramframe.IsShown():
##        paramframe.Hide()
##    anaframe = wx.FindWindowById(460)
##    if anaframe.IsShown():
##        anaframe.Hide()
##    dosframe = wx.FindWindowById(461)
##    if dosframe.IsShown():
##        dosframe.Hide()
##    userframe = wx.FindWindowById(462)
##    if userframe.IsShown():
##        userframe.Hide()
##    wizardframe = wx.FindWindowById(463)
##    if wizardframe.IsShown():
##        wizardframe.Hide()
class WizardEnd(wx.Frame):
    global enter,line1,line2,line3,keyvalue,postes,users
    def __init__(self, parent, id, title):
        global line1,line2,line3,keyvalue,postes,users
        wx.Frame.__init__(self, parent, id, title, size=(250, 150),style=wx.FRAME_SHAPED |wx.FRAME_NO_TASKBAR|wx.NO_BORDER)

        self.font = wx.Font(8, wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL, 
		wx.FONTWEIGHT_BOLD, False, 'Comic Sans MS')

        self.hasShape=False
        self.delta=(0,0)

        self.image_file = 'img/info-normal.gif'
        self.bmp = wx.Bitmap(self.image_file, wx.BITMAP_TYPE_GIF)
        
        self.bitmap = wx.Bitmap('img/info-normal.png', wx.BITMAP_TYPE_PNG)
        self.wizard = wx.Bitmap('img/info-normal.png', wx.BITMAP_TYPE_PNG)
        self.wizarda = wx.Bitmap('img/info-appui.png', wx.BITMAP_TYPE_PNG)
        self.wizardr = wx.Bitmap('img/info-rollover.png', wx.BITMAP_TYPE_PNG)
        self.close = wx.Bitmap('img/close-normal.png', wx.BITMAP_TYPE_PNG)
        self.closer = wx.Bitmap('img/info-close.png', wx.BITMAP_TYPE_PNG)


        self.SetClientSize((self.bitmap.GetWidth(), self.bitmap.GetHeight()))

        if wx.Platform == '__WXGTK__':
            self.Bind(wx.EVT_WINDOW_CREATE, self.SetNoteShape)
        else: self.SetNoteShape()

        #self.SetTransparent(220)
        self.Bind(wx.EVT_PAINT, self.OnPaint)
        self.Bind(wx.EVT_LEFT_DOWN, self.OnLeftDown)
        self.Bind(wx.EVT_MOTION, self.OnMouseMove)

        self.bitmapRegion = wx.RegionFromBitmap(self.bitmap)
        self.wizardRegion = wx.RegionFromBitmap(self.wizard)
        self.closeRegion = wx.RegionFromBitmap(self.close)
        
        self.wizardRegion.IntersectRegion(self.bitmapRegion)
        self.wizardRegion.Offset(60, 98)

        self.closeRegion.IntersectRegion(self.bitmapRegion)
        self.closeRegion.Offset(192, 7)
      
        self.wdc = wx.ClientDC(self)
        self.wdc.DrawBitmap(self.bitmap, 0, 0, True)

        self.Show(True)
        self.Fit()
        self.Centre()
        enter=False


    def SetNoteShape(self, *event):
        region = wx.RegionFromBitmap(self.bmp)
        self.hasShape=self.SetShape(region)




    def Draw(self):
        global line1,line2,line3
        self.wdc.font1 = wx.Font(8, wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_NORMAL, False)
        self.wdc.SetTextBackground(wx.NullColour)
        self.wdc.SetTextForeground('#FFFFFF')
        self.wdc.SetFont(self.wdc.font1)
        self.wdc.DrawText(line1,10,40)
        self.wdc.DrawText(line2,10,55)
        self.wdc.DrawText(line3,10,70)
        self.Show ( True )

    def OnPaint(self, event):
        wx.BufferedPaintDC(self,self.bitmap)
        self.Draw()
        event.Skip()








    def OnLeftDown(self, event):
        pos = event.GetPosition()
        if self.closeRegion.ContainsPoint(pos):
            self.Close()
        elif self.wizardRegion.ContainsPoint(pos):
            wx.BufferedDC(wx.ClientDC(self),self.wizarda)
            if line1=="Licence périmée.":
                try:
                    wizardframe = wx.FindWindowById(463)
                    if wizardframe.IsShown():
                        wizardframe.Show()
                        self.Close()
                except:
                    WizardActivation(None, 463, 'Chronos Monitor Wizard')
                    self.Close()
            else:
                self.Close()          
        x, y = self.ClientToScreen(event.GetPosition())
        ox, oy = self.GetPosition()
        dx = x - ox
        dy = y - oy
        self.delta = ((dx, dy))


    def OnMouseMove(self, event):
        global enter
        if event.LeftIsDown()==False:
            pos = event.GetPosition()
            if self.closeRegion.ContainsPoint(pos):
                wx.BufferedDC(wx.ClientDC(self),self.closer)
                self.Draw()
                enter=True
            elif self.wizardRegion.ContainsPoint(pos):
                wx.BufferedDC(wx.ClientDC(self),self.wizardr)
                self.Draw()
                enter=True
            else:
                if enter==True:
                    wx.BufferedDC(wx.ClientDC(self),self.bitmap)
                    self.Draw()
                    enter=False
        if event.Dragging() and event.LeftIsDown():
            x, y = self.ClientToScreen(event.GetPosition())
            fp = (x - self.delta[0], y - self.delta[1])
            self.Move(fp)
        event.Skip()


class WizardSelect(wx.Frame):
    global jak,enter,line1,line2,line3,keyvalue,postes,users,dc,box,paned,ElChaloR,posteid
    def __init__(self, parent, id, title):
        global jak,line1,line2,line3,keyvalue,postes,users,dc,box,paned,ElChaloR,oscurdir,posteid
        wx.Frame.__init__(self, parent, id, title, size=(250, 150),style=wx.FRAME_SHAPED |wx.FRAME_NO_TASKBAR|wx.NO_BORDER)

        self.font = wx.Font(11, wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL, 
		wx.FONTWEIGHT_BOLD, False, 'Comic Sans MS')

        #self.panel=wx.Panel(self,-1)

        self.hasShape=False
        self.delta=(0,0)

        self.image_file = 'img/fond-choix.gif'
        self.bmp = wx.Bitmap(self.image_file, wx.BITMAP_TYPE_GIF)
        #bg=wx.StaticBitmap(self.panel, wx.ID_ANY, bmp, (0, 0))
        
        self.bitmap = wx.Bitmap('img/wizard_0.png', wx.BITMAP_TYPE_PNG)
        self.wizard = wx.Bitmap('img/valider-normal.png', wx.BITMAP_TYPE_PNG)
        #self.wizardf = wx.Bitmap('img/validerf.png', wx.BITMAP_TYPE_PNG)
        self.wizarda = wx.Bitmap('img/wizard_appui.png', wx.BITMAP_TYPE_PNG)
        self.wizardr = wx.Bitmap('img/wizard_rollover.png', wx.BITMAP_TYPE_PNG)
        self.close = wx.Bitmap('img/close-normal.png', wx.BITMAP_TYPE_PNG)
 #       self.closef = wx.Bitmap('img/close-fond2.png', wx.BITMAP_TYPE_PNG)
        self.closer = wx.Bitmap('img/wizard_close.png', wx.BITMAP_TYPE_PNG)
        self.fond1 = wx.Bitmap('img/wizard-fond.png', wx.BITMAP_TYPE_PNG)
        self.fond2 = wx.Bitmap('img/wizard-fond.png', wx.BITMAP_TYPE_PNG)

        def get_main_dir():
            try:
                sys.frozen
            except AttributeError:
                path = sys.argv[0]
            else:
                path = sys.executable
            return os.path.dirname(os.path.abspath(path))

        oscurdir=get_main_dir()
        
        #bmp = wx.Bitmap(image_file)
        #self.bg=wx.StaticBitmap(self, wx.ID_ANY, bmp, (0, 0))
        self.SetClientSize((self.bitmap.GetWidth(), self.bitmap.GetHeight()))

        if wx.Platform == '__WXGTK__':
            self.Bind(wx.EVT_WINDOW_CREATE, self.SetNoteShape)
        else: self.SetNoteShape()

        enter=False         
        #MyButton(self.panel,-1,(47,168),'img/sync-normal.png','img/sync-rollover.png','img/appui-sync.png')
        #self.SetTransparent(220)
        self.Bind(wx.EVT_PAINT, self.OnPaint)
        self.Bind(wx.EVT_LEFT_DOWN, self.OnLeftDown)
        self.Bind(wx.EVT_LEFT_DOWN, self.OnLeftDown)
        self.Bind(wx.EVT_MOTION, self.OnMouseMove)

        self.bitmapRegion = wx.RegionFromBitmap(self.bitmap)
        self.wizardRegion = wx.RegionFromBitmap(self.wizard)
        self.closeRegion = wx.RegionFromBitmap(self.close)


        self.wizardRegion.IntersectRegion(self.bitmapRegion)
        self.wizardRegion.Offset(58, 520)

        self.closeRegion.IntersectRegion(self.bitmapRegion)
        self.closeRegion.Offset(190, 10)
        jak='2164691737824342'
        posteid=""
      
##        regroot=_winreg.HKEY_LOCAL_MACHINE
##        hKey=_winreg.OpenKey(regroot,"SOFTWARE\Microsoft\Cryptography",0,_winreg.KEY_READ)
##        value, type=_winreg.QueryValueEx(hKey, "MachineGuid")
##        print value
        
        for x in range(1,int(users['nombre'])+1):
            users["Checked",int(x)]=False
        self.dc = wx.ClientDC(self)
        self.dc.DrawBitmap(self.bitmap, 0, 0, True)
        #self.bdc = wx.BufferedDC(self.cdc)
        #self.nkey=wx.TextCtrl(self,wx.ID_ANY,'',pos=(20,39),size=(180,20))
        self.Show(True)
        self.Fit()
        self.Centre()
#        key=""
        

##    def OnClose(self, event):
##        self.tskic.Destroy()
##        self.Destroy()
    def OnEraseBackground1(self, evt):
        """
        Add a picture to the background
        """
        # yanked from ColourDB.py
        dc = evt.GetDC()
 
##        if not dc:
##            dc = wx.ClientDC(self)
##            rect = self.GetUpdateRegion().GetBox()
##            dc.SetClippingRect(rect)
        dc.Clear()
        bmp = wx.Bitmap("img/haut.png")
        dc.DrawBitmap(bmp, 0, 0)

    def SetNoteShape(self, *event):
        #region=wx.RegionFromBitmapColour(self.bitmap,'#000000',0)
        region = wx.RegionFromBitmap(self.bmp)
        self.hasShape=self.SetShape(region)


    def OnClicked(self, event):
        #print 'event reached frame class'
        event.Skip()


    def OnKey(self,event):
        global key
        key=event.GetString()

    def OnRadio(self,event):
        global posteid,postehip
        hipe=event.GetId()
        #print hipe
        p=0
        hip=""
        for char in str(hipe):
            if p >2:
                hip=hip+char
            p+=1
        #print hip
        posteid=postes["ID",int(hip)]
        postehip=int(hip)
        #print posteid
        
    def OnCheck(self,event):
        global uzerid,panelp,box
        uzer=event.GetId()
        p=0
        hip=""
        for char in str(uzer):
            if p >2:
                hip=hip+char
            p+=1
        #print hip
       # if self.dc.box[int(hip)].GetValue():
        user = wx.FindWindowById(int(uzer))
        if user.GetValue():
            users["Checked",int(hip)]=True
            #print 'oui'
        else:
            users["Checked",int(hip)]=False
            #print 'non'
        #print uzer




    def OnApply(self,event):
        global posteid
        for x in range(1,int(users['nombre'])+1):
            #print self.dc.box[x].GetValue()
            pass
    def DShow(self):
        self.dc.DrawText("Veuillez choisir votre poste :",10,30)
        self.dc.DrawText("Veuillez choisir les utilisateurs du poste :",10,280)

    def Draw(self):
        global postes,users,dc,box,panelp,posteid,postehip
        self.dc.SetFont(self.font)
        self.dc.SetTextForeground('#FFFFFF')
##        self.dc.DrawBitmap(self.bitmap, 0, 0, True)
##        self.dc.DrawBitmap(self.close, 200, 12, True)
##        self.dc.DrawBitmap(self.wizard, 60, 520, True)
        self.dc.font1 = wx.Font(8, wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_NORMAL, False)
        self.dc.SetTextBackground(wx.NullColour)
        self.dc.SetTextForeground('#FFFFFF')
        self.dc.SetFont(self.dc.font1)
        #self.dc.SetTextSize(8)
        self.dc.DrawText("Veuillez choisir votre poste :",10,30)
#        self.dc.panel=WizardPanelPostes(self.dc,postes)
        self.dc.panel=scrolled.ScrolledPanel(self,-1,(10,50),(200,200), style=wx.SUNKEN_BORDER)
##        self.dc.panel.Bind(wx.EVT_ERASE_BACKGROUND, self.OnEraseBackground1)
        self.dc.panel.SetBackgroundColour('#EAEAE9')
        self.dc.panel.SetupScrolling(scroll_x=True,scroll_y=True)
        self.dc.DrawBitmap(self.fond1, 10, 60, True)
        #self.dc.panel=MyScrollPanel(self.dc)
        self.dc.postbox=wx.BoxSizer(wx.VERTICAL)
        self.dc.radio={}
        for x in range(1,int(postes['nombre'])+1):
            posy=(int(x)*20)
            idx=4000+int(x)
            self.dc.radio[x]=wx.RadioButton(self.dc.panel,idx,label=str(postes['posteNAME',int(x)]))
            self.dc.postbox.Add(self.dc.radio[x],wx.LEFT)
            self.dc.radio[x].Bind(wx.EVT_RADIOBUTTON, self.OnRadio)
            if int(postes['selected'])==int(x):
                self.dc.radio[x].SetValue(True)
                posteid=postes['ID',x]
                postehip=x
            if posteid=="":
                posteid=idx
                postehip=postes['nombre']
        self.dc.panel.SetSizer(self.dc.postbox)
        self.dc.postbox.FitInside(self.dc.panel)
        #self.dc.postbox.Bind(wx.EVT_ERASE_BACKGROUND, self.OnEraseBackground1)
#============================================================
        self.dc.DrawText("Veuillez choisir les utilisateurs du poste :",10,280)
        self.dc.panelp=scrolled.ScrolledPanel(self,-1,(10,300),(200,200), style=wx.SUNKEN_BORDER)
        self.dc.panelp.SetupScrolling(scroll_x=True,scroll_y=True)
        self.dc.panelp.SetBackgroundColour('#EAEAE9')
        self.dc.DrawBitmap(self.fond2, 10, 300, True)
        #self.dc.panel=MyScrollPanel(self.dc)
        self.dc.postboxp=wx.BoxSizer(wx.VERTICAL)
        self.dc.box={}
        for x in range(1,int(users['nombre'])+1):
            #print x
            posy=(int(x)*10)
            idx=1000+int(x)
            self.dc.box[x]=wx.CheckBox(self.dc.panelp,idx,label=str(users['nom',int(x)])+' '+str(users['prenom',int(x)]))
            self.dc.postboxp.Add(self.dc.box[x],wx.LEFT)
            self.dc.box[x].Bind(wx.EVT_CHECKBOX, self.OnCheck)
        self.dc.panelp.SetSizer(self.dc.postboxp)
        self.dc.postboxp.FitInside(self.dc.panelp)

    def OnPaint(self, event):
        wx.BufferedPaintDC(self,self.bitmap)
        self.Draw()
        

#============================================================        
        #self.dc.nkey.CanPaste()
        #self.dc.nkey.SetEditable(True)
        #self.dc.nkey.SetValue("CLEF DACTIVATION")
##        self.dc.nkey.Bind(wx.EVT_TEXT, self.OnKey)
##        self.dc.DrawText(str(line1),10,90)
##        self.dc.DrawText(str(line2),10,105)
##        self.dc.DrawText(str(line3),10,120)##        self.dc.DrawBitmap(self.users, 22, 80, True)
##        self.dc.DrawBitmap(self.dossiers, 22, 120, True)
##        self.dc.DrawBitmap(self.analyse, 22, 160, True)
        #self.dc.DrawBitmap(self.reduce, 180, 45, True)
        #self.sync.Bind(wx.EVT_ENTER,self.OnSync)
        #MyButton(self.dc,-1,(51,168),'img/sync-normal2.png','img/sync-rollover2.png','img/appui-sync2.png')
        event.Skip()








    def OnLeftDown(self, event):
        global jak,line1,line2,line3,keyvalue,dc,posteid,ElChaloR,posteid,postehip,oscurdir
        #self.bdc = wx.BufferedDC(self.cdc)
        pos = event.GetPosition()
##        self.dc.nkey.SelectAll()
##        self.key = self.dc.nkey.GetValue()
##        self.dc.nkey.Clear()
#        print "+"+repr(self.key)+"+"
        if self.closeRegion.ContainsPoint(pos):
            self.Close()
        elif self.wizardRegion.ContainsPoint(pos):
            line3=""
            if postes['selected']!=False:
                if postes["ID",int(postes['selected'])]!=posteid:
                    #print 'bingo1'
                    conn_string = "host='88.191.122.246' dbname='chronos-monitor.com' user='user' password='gaor867'"
                    conn = psycopg2.connect(conn_string)
                    curs = conn.cursor()               
                    if postes['selected']!=False:
                        intostr="""UPDATE postes SET guid='', activated='0' WHERE id='"""+str(postes["ID",int(postes['selected'])])+"""';"""

                        result=curs.execute(intostr)
                        #print 'bingo3'
                        

                    intostr="""UPDATE postes SET guid='"""+str(keyvalue)+"""', activated='1' WHERE id='"""+str(posteid)+"""';"""
                            
                    result=curs.execute(intostr)
                    curs.close()
                    conn.close()
            else:
                    #print 'bingo2-'+str(posteid)
                    conn_string = "host='88.191.122.246' dbname='chronos-monitor.com' user='user' password='gaor867'"
                    conn = psycopg2.connect(conn_string)
                    curs = conn.cursor()
                    intostr="""UPDATE postes SET guid='"""+str(keyvalue)+"""', activated='1' WHERE id='"""+str(posteid)+"""';"""
                    try:
                        result=curs.execute(intostr)
                        conn.commit()
                    except:
                        exceptionType, exceptionValue, exceptionTraceback = sys.exc_info()
                        #print "Database connection failed!\n ->%s" % (exceptionValue)
                    curs.close()
                    conn.close()
            try:
                TchemFSF=oscurdir+os.sep+'wok'+os.sep+'conf'+os.sep+'local.gwh'
                #fft=open(TchemFSF, mode ='w+')
            except:
                line2='erreur ouverture fichier'
            try:
                pass
            except:
                line2='erreur ouverture string'
##            try:
##                
##            except:
##                line3='erreur obj'
            
            def Gencrypt(output,TchemFSF):
                global jak
                encryptor=AES.new(str(ElChaloR[0:24]), AES.MODE_CBC,jak)
                chunksize=(64*1024)
                mlogfile = open(TchemFSF, 'wb')
                ret=''
                while True:
                    chunk = output.read(n=chunksize)
                    #print 'chunk='+repr(chunk)
                    if len(chunk)==0:
                        break
                    elif len(chunk)%16!=0:
                        chunk += ' ' * (16-len(chunk) % 16 )                
                    ret=ret+chunk
                #print 'ret='+repr(ret)
                djunky=encryptor.encrypt(ret)
                mlogfile.write(djunky)
                mlogfile.close()
            def Twrite(data):
                fft.write(data)
            try:
                strin=postes["PID"]+'\t'+postes["ID",+int(postehip)]+'\t'+postes["posteNAME",+int(postehip)]+'\t'+postes["dateFin",+int(postehip)]+'\t'+str(key)+'\t'+postes["ADMINID"]+'\n'
                for x in range(1,int(users['nombre'])+1):
                    if users["Checked",x]==True:
                        strin=strin+users["ID",x]+'\t'+users["nom",x]+'\t'+users["prenom",x]+'\t'+users["login",x]+'\t'+users["pass",x]+'\n'
            except:
                line2='dic error'
            try:
                output = StringIO.StringIO(strin)
            except:
                line3='string error'
            try:
                Gencrypt(output,TchemFSF)
            except:
                line3=line3+'-erreur encription'
            try:
                line1="votre poste est maintenant configuré"
                line2=""
            except:
                line1="erreur dans la configuration de votre poste"


            self.Close()
            WizardEnd(None, 469, 'Chronos Monitor')    
        x, y = self.ClientToScreen(event.GetPosition())
        ox, oy = self.GetPosition()
        dx = x - ox
        dy = y - oy
        self.delta = ((dx, dy))


    def OnMouseMove(self, event):
        global enter,line1,line2,line3
        pos = event.GetPosition()
        if self.closeRegion.ContainsPoint(pos):
            wx.BufferedDC(wx.ClientDC(self),self.closer)
            self.DShow()
            enter=True
        elif self.wizardRegion.ContainsPoint(pos):
            #self.dc.DrawBitmap(self.wizardf, 22, 40, True)
            wx.BufferedDC(wx.ClientDC(self),self.wizardr)
            self.DShow()
            enter=True
        else:
            if enter==True:
                wx.BufferedDC(wx.ClientDC(self),self.bitmap)
                self.DShow()
                enter=False
##            self.dc.DrawBitmap(self.wizard, 60, 520, True)            
##        if event.LeftIsDown()==False:
##            pos = event.GetPosition()
##            if self.wizardRegion.ContainsPoint(pos):
##                #self.dc.DrawBitmap(self.wizardf, 22, 40, True)
##                self.dc.DrawBitmap(self.wizardr, 60, 60, True)
##                enter=True
##            else:
##                if enter==True:
##                    self.dc.DrawBitmap(self.bitmap, 0, 0, True)
##                    self.dc.DrawBitmap(self.close, 201, 12, True)
##            ##        self.dc.sincro=self.dc.DrawBitmap(self.sync, 51, 168, True)
##                    #self.oversincro=self.dc.DrawBitmap(self.oversync, 51, 168, True)
##                    #self.oversincro.Hide()
##                    self.dc.DrawBitmap(self.wizard, 60, 60, True)
##                    self.dc.font1 = wx.Font(12, wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_NORMAL, False, 'AgencyFB-Regular')
##                    self.dc.SetTextBackground(wx.NullColour)
##                    self.dc.SetTextForeground('#6C8D91')
##                    self.dc.SetFont(self.dc.font1)
##                    #self.dc.SetTextSize(8)
##                    self.dc.DrawText("Veuillez saisir la clef d'activation :",10,20)
##                    self.dc.nkey.Show()
##                    self.dc.DrawText(str(line1),10,90)
##                    self.dc.DrawText(str(line2),10,105)
##                    self.dc.DrawText(str(line3),10,120)
##                    enter=False

        if event.Dragging() and event.LeftIsDown():
            x, y = self.ClientToScreen(event.GetPosition())
            fp = (x - self.delta[0], y - self.delta[1])
            self.Move(fp)
        #print enter
        event.Skip()

class UserSelect(wx.Frame):
    global jak,enter,line1,line2,line3,keyvalue,poste,user,dc,box,paned,ElChaloR
    def __init__(self, parent, id, title):
        global jak,line1,line2,line3,keyvalue,poste,user,dc,box,paned,ElChaloR,oscurdir
        wx.Frame.__init__(self, parent, id, title, size=(250, 150),style=wx.FRAME_SHAPED |wx.FRAME_NO_TASKBAR|wx.NO_BORDER)

        self.font = wx.Font(11, wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL, 
		wx.FONTWEIGHT_BOLD, False, 'Comic Sans MS')

        #self.panel=wx.Panel(self,-1)

        self.hasShape=False
        self.delta=(0,0)

        self.image_file = 'img/fond-choix.gif'
        self.bmp = wx.Bitmap(self.image_file, wx.BITMAP_TYPE_GIF)
        #bg=wx.StaticBitmap(self.panel, wx.ID_ANY, bmp, (0, 0))
        
        self.bitmap = wx.Bitmap('img/wizard_0.png', wx.BITMAP_TYPE_PNG)
        self.wizard = wx.Bitmap('img/valider-normal.png', wx.BITMAP_TYPE_PNG)
        #self.wizardf = wx.Bitmap('img/validerf.png', wx.BITMAP_TYPE_PNG)
        self.wizarda = wx.Bitmap('img/wizard_appui.png', wx.BITMAP_TYPE_PNG)
        self.wizardr = wx.Bitmap('img/wizard_rollover.png', wx.BITMAP_TYPE_PNG)
        self.close = wx.Bitmap('img/close-normal.png', wx.BITMAP_TYPE_PNG)
 #       self.closef = wx.Bitmap('img/close-fond2.png', wx.BITMAP_TYPE_PNG)
        self.closer = wx.Bitmap('img/wizard_close.png', wx.BITMAP_TYPE_PNG)
        self.fond1 = wx.Bitmap('img/wizard-fond.png', wx.BITMAP_TYPE_PNG)
        self.fond2 = wx.Bitmap('img/wizard-fond.png', wx.BITMAP_TYPE_PNG)

        def get_main_dir():
            try:
                sys.frozen
            except AttributeError:
                path = sys.argv[0]
            else:
                path = sys.executable
            return os.path.dirname(os.path.abspath(path))

        oscurdir=get_main_dir()
        
        #bmp = wx.Bitmap(image_file)
        #self.bg=wx.StaticBitmap(self, wx.ID_ANY, bmp, (0, 0))
        self.SetClientSize((self.bitmap.GetWidth(), self.bitmap.GetHeight()))

        if wx.Platform == '__WXGTK__':
            self.Bind(wx.EVT_WINDOW_CREATE, self.SetNoteShape)
        else: self.SetNoteShape()

        enter=False         
        #MyButton(self.panel,-1,(47,168),'img/sync-normal.png','img/sync-rollover.png','img/appui-sync.png')
        #self.SetTransparent(220)
        self.Bind(wx.EVT_PAINT, self.OnPaint)
        self.Bind(wx.EVT_LEFT_DOWN, self.OnLeftDown)
        self.Bind(wx.EVT_LEFT_DOWN, self.OnLeftDown)
        self.Bind(wx.EVT_MOTION, self.OnMouseMove)

        self.bitmapRegion = wx.RegionFromBitmap(self.bitmap)
        self.wizardRegion = wx.RegionFromBitmap(self.wizard)
        self.closeRegion = wx.RegionFromBitmap(self.close)


        self.wizardRegion.IntersectRegion(self.bitmapRegion)
        self.wizardRegion.Offset(58, 520)

        self.closeRegion.IntersectRegion(self.bitmapRegion)
        self.closeRegion.Offset(190, 10)
        jak='2164691737824342'
      
##        regroot=_winreg.HKEY_LOCAL_MACHINE
##        hKey=_winreg.OpenKey(regroot,"SOFTWARE\Microsoft\Cryptography",0,_winreg.KEY_READ)
##        value, type=_winreg.QueryValueEx(hKey, "MachineGuid")
##        print value
        

        self.dc = wx.ClientDC(self)
        self.dc.DrawBitmap(self.bitmap, 0, 0, True)
        #self.bdc = wx.BufferedDC(self.cdc)
        #self.nkey=wx.TextCtrl(self,wx.ID_ANY,'',pos=(20,39),size=(180,20))
        self.Show(True)
        self.Fit()
        self.Centre()
#        key=""
        

##    def OnClose(self, event):
##        self.tskic.Destroy()
##        self.Destroy()
    def OnEraseBackground1(self, evt):
        """
        Add a picture to the background
        """
        # yanked from ColourDB.py
        dc = evt.GetDC()
 
##        if not dc:
##            dc = wx.ClientDC(self)
##            rect = self.GetUpdateRegion().GetBox()
##            dc.SetClippingRect(rect)
        dc.Clear()
        bmp = wx.Bitmap("img/haut.png")
        dc.DrawBitmap(bmp, 0, 0)

    def SetNoteShape(self, *event):
        #region=wx.RegionFromBitmapColour(self.bitmap,'#000000',0)
        region = wx.RegionFromBitmap(self.bmp)
        self.hasShape=self.SetShape(region)


    def OnClicked(self, event):
        #print 'event reached frame class'
        event.Skip()


    def OnKey(self,event):
        global key
        key=event.GetString()

        
    def OnCheck(self,event):
        global users
        uzer=event.GetId()
        hip=event.GetId()

        
       # if self.dc.box[int(hip)].GetValue():
        tuser = wx.FindWindowById(int(uzer))
        if tuser.GetValue():
            users["Checked",int(hip)]=True
        else:
            users["Checked",int(hip)]=False
            print 'non'
        #print uzer

    def ChargePoste(self):
        global poste,users
        TchemFSF=oscurdir+os.sep+'wok'+os.sep+'conf'+os.sep+'local.gwh'
        fft=open(TchemFSF, mode ='rb')
        output = StringIO.StringIO(fft.read())
        decoutput=StringIO.StringIO()
        #output.write(fft.read())
        fft.close()
        def Gdecrypt(output,decoutput):
            global jak
            xdecryptor=AES.new(str(ElChaloR[0:24]), AES.MODE_CBC,jak)
            chunksize=(64*1024)
            rep=''
            while True:
                chunk=''
                chunk=output.read(n=chunksize)
                if len(chunk)==0:
                    break
                elif len(chunk)%16!=0:
                    chunk += ' ' * (16-len(chunk) % 16 )
                rep=rep+xdecryptor.decrypt(chunk)
            decoutput.write(rep)
            return decoutput

        Gdecrypt(output,decoutput)
        lines={}
        lines = decoutput.getvalue()
        #print 'lines-'+repr(lines)
        #lo=len(lines)
        #lines = decoutput.readlines()
        #print decoutput.getvalue()
        p=0
        poste={}
        user={}
        l=0
        poste["PID"]=""
        poste["ID"]=""
        poste["posteNAME"]=""
        poste["Date"]=""
        poste["GUID"]=""
        poste["ADMINID"]=""
        T=False
        for char in lines:
            if char=='\t':
                p+=1
                continue
            if char=='\n':
                T=True
                p=0
                l+=1
                user["ID",l]=""
                user["nom",l]=""
                user["prenom",l]=""
                user["login",l]=""
                user["pass",l]=""
                user["Checked",l]=False
                continue
            if p==0 and l==0:poste["PID"]=poste["PID"]+char
            if p==1 and l==0:poste["ID"]=poste["ID"]+char
            if p==2 and l==0:poste["posteNAME"]=poste["posteNAME"]+char
            if p==3 and l==0:poste["Date"]=poste["Date"]+char
            if p==4 and l==0:poste["GUID"]=poste["GUID"]+char
            if p==5 and l==0:poste["ADMINID"]=poste["ADMINID"]+char
            if T==True and p==0:user["ID",l]= user["ID",l]+char
            if T==True and p==1:user["nom",l]= user["nom",l]+char
            if T==True and p==2:user["prenom",l]= user["prenom",l]+char
            if T==True and p==3:user["login",l]= user["login",l]+char
            if T==True and p==4:user["pass",l]= user["pass",l]+char
        user["nombre"]=l
        try:
            conn_string = "host='88.191.122.246' dbname='chronos-monitor.com' user='user' password='gaor867'"
            conn = psycopg2.connect(conn_string)
            curs = conn.cursor()
            result=curs.execute("SELECT nom,prenom,id,admin,login,pass FROM users WHERE idadmin='"+str(poste["ADMINID"])+"';" )
            result=curs.fetchall()
            u=1
            if result:
                active=True
                users={}
                for chain in result:
                    #print chain
                    users['nom',u]=""
                    users['prenom',u]=""
                    users['ID',u]=""
                    users['admin',u]=""
                    users['pass',u]=""
                    users['login',u]=""
                    users["Checked",u]=False
                    #users['adminID',u]=""
                    p=0
                    for char in chain:
                        #print char
                        if p==0:users['nom',u]=users['nom',u]+str(char)
                        if p==1:users['prenom',u]=users['prenom',u]+str(char)
                        if p==2:users['ID',u]=users['ID',u]+str(char)
                        if p==3:users['admin',u]=users['admin',u]+str(char)
                        if p==4:users['login',u]=users['login',u]+str(char)
                        if p==5:users['pass',u]=users['pass',u]+str(char)
                        p+=1
                    users['nombre']=u
                    u+=1
        except:
            line1="Connection internet indisponible"

    def OnApply(self,event):
        global posteid
        for x in range(1,int(user['nombre'])+1):
            pass
    def DShow(self):
        self.dc.DrawText("Veuillez choisir les utilisateurs du poste :",10,30)

    def Draw(self):
        global poste,users,dc,box,panelp
        self.dc.SetFont(self.font)
        self.dc.SetTextForeground('#6C8D91')
        self.dc.font1 = wx.Font(8, wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_NORMAL, False)
        self.dc.SetTextBackground(wx.NullColour)
        self.dc.SetTextForeground('#6C8D91')
        self.dc.SetFont(self.dc.font1)
        self.dc.DrawText("Veuillez choisir les utilisateurs du poste :",10,30)
        self.dc.panelp=scrolled.ScrolledPanel(self,-1,(10,50),(200,300), style=wx.SUNKEN_BORDER)
        self.dc.panelp.SetupScrolling(scroll_x=True,scroll_y=True)
        self.dc.panelp.SetBackgroundColour('#EAEAE9')
        self.dc.DrawBitmap(self.fond2, 10, 50, True)
        self.dc.postboxp=wx.BoxSizer(wx.VERTICAL)
        self.dc.box={}
        for x in range(1,int(users['nombre'])+1):
            #print x
            posy=(int(x)*10)
            idx=int(x)
            self.dc.box[x]=wx.CheckBox(self.dc.panelp,idx,label=str(users['nom',int(x)])+' '+str(users['prenom',int(x)]))
            self.dc.postboxp.Add(self.dc.box[x],wx.LEFT)
            self.dc.box[x].Bind(wx.EVT_CHECKBOX, self.OnCheck)
        self.dc.panelp.SetSizer(self.dc.postboxp)
        self.dc.postboxp.FitInside(self.dc.panelp)

    def OnPaint(self, event):
        wx.BufferedPaintDC(self,self.bitmap)
        self.ChargePoste()
        self.Draw()
        event.Skip()








    def OnLeftDown(self, event):
        global jak,line1,line2,line3,keyvalue,dc,posteid,ElChaloR,posteid,postehip,oscurdir,poste,users
        pos = event.GetPosition()
        if self.closeRegion.ContainsPoint(pos):
            self.Close()
        elif self.wizardRegion.ContainsPoint(pos):
            line3=""
            try:
                TchemFSF=oscurdir+os.sep+'wok'+os.sep+'conf'+os.sep+'local.gwh'
            except:
                line2='erreur ouverture fichier'
            try:
                pass
            except:
                line2='erreur ouverture string'
##            try:
##                
##            except:
##                line3='erreur obj'
            
            def Gencrypt(output,TchemFSF):
                global jak
                encryptor=AES.new(str(ElChaloR[0:24]), AES.MODE_CBC,jak)
                chunksize=(64*1024)
                mlogfile = open(TchemFSF, 'wb')
                ret=''
                while True:
                    chunk = output.read(n=chunksize)
                    #print 'chunk='+repr(chunk)
                    if len(chunk)==0:
                        break
                    elif len(chunk)%16!=0:
                        chunk += ' ' * (16-len(chunk) % 16 )                
                    ret=ret+chunk
                #print 'ret='+repr(ret)
                djunky=encryptor.encrypt(ret)
                mlogfile.write(djunky)
                mlogfile.close()
            def Twrite(data):
                fft.write(data)
            #try:
            strin=poste["PID"]+'\t'+poste["ID"]+'\t'+poste["posteNAME"]+'\t'+poste["Date"]+'\t'+poste["GUID"]+'\t'+poste["ADMINID"]+'\n'
            for x in range(1,int(users['nombre'])+1):
                if users["Checked",x]==True:
                    strin=strin+users["ID",x]+'\t'+users["nom",x]+'\t'+users["prenom",x]+'\t'+users["login",x]+'\t'+users["pass",x]+'\n'
            #except:
                #line3='dic error'
            try:
                output = StringIO.StringIO(strin)
                #print 'strin='+repr(strin)
            except:
                line3='string error'
            try:
                Gencrypt(output,TchemFSF)
            except:
                line2='erreur encription'
            try:
                line1="Les utilisateurs sont maintenant configurés"
                line2=""
            except:
                line1="erreur dans la configuration de votre poste"
                line2=""


            self.Close()
            WizardEnd(None, 468, 'Chronos Monitor')    
        x, y = self.ClientToScreen(event.GetPosition())
        ox, oy = self.GetPosition()
        dx = x - ox
        dy = y - oy
        self.delta = ((dx, dy))


    def OnMouseMove(self, event):
        global enter,line1,line2,line3
        pos = event.GetPosition()
        if self.closeRegion.ContainsPoint(pos):
            wx.BufferedDC(wx.ClientDC(self),self.closer)
            self.DShow()
            enter=True
        elif self.wizardRegion.ContainsPoint(pos):
            wx.BufferedDC(wx.ClientDC(self),self.wizardr)
            self.DShow()
            enter=True
        else:
            if enter==True:
                wx.BufferedDC(wx.ClientDC(self),self.bitmap)
                self.DShow()
                enter=False


        if event.Dragging() and event.LeftIsDown():
            x, y = self.ClientToScreen(event.GetPosition())
            fp = (x - self.delta[0], y - self.delta[1])
            self.Move(fp)
        #print enter
        event.Skip()

           
class WizardActivation(wx.Frame):
    global enter,line1,line2,keyvalue,postes,users,key
    def __init__(self, parent, id, title):
        global line1,line2,keyvalue,postes,users,key
        wx.Frame.__init__(self, parent, id, title, size=(250, 150),style=wx.FRAME_SHAPED |wx.FRAME_NO_TASKBAR|wx.NO_BORDER)

        self.font = wx.Font(11, wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL, 
		wx.FONTWEIGHT_BOLD, False, 'Comic Sans MS')

        #self.panel=wx.Panel(self,-1)

        self.hasShape=False
        self.delta=(0,0)

        self.image_file = 'img/fond-small-wizard.gif'
        self.bmp = wx.Bitmap(self.image_file, wx.BITMAP_TYPE_GIF)
        #bg=wx.StaticBitmap(self.panel, wx.ID_ANY, bmp, (0, 0))
        
        self.bitmap = wx.Bitmap('img/code_0.png', wx.BITMAP_TYPE_PNG)
        self.wizard = wx.Bitmap('img/valider-normal.png', wx.BITMAP_TYPE_PNG)
        #self.wizardf = wx.Bitmap('img/validerf.png', wx.BITMAP_TYPE_PNG)
        self.wizarda = wx.Bitmap('img/code_appui.png', wx.BITMAP_TYPE_PNG)
        self.wizardr = wx.Bitmap('img/code_rollover.png', wx.BITMAP_TYPE_PNG)
        self.close = wx.Bitmap('img/close-normal.png', wx.BITMAP_TYPE_PNG)
        self.closer = wx.Bitmap('img/code_close.png', wx.BITMAP_TYPE_PNG)


        
        #bmp = wx.Bitmap(image_file)
        #self.bg=wx.StaticBitmap(self, wx.ID_ANY, bmp, (0, 0))
        self.SetClientSize((self.bitmap.GetWidth(), self.bitmap.GetHeight()))

        if wx.Platform == '__WXGTK__':
            self.Bind(wx.EVT_WINDOW_CREATE, self.SetNoteShape)
        else: self.SetNoteShape()

        line1="Rendez vous sur chronosmonitor.com"
        line2="Pour obtenir une clef d'activation"
        enter=False         
        #MyButton(self.panel,-1,(47,168),'img/sync-normal.png','img/sync-rollover.png','img/appui-sync.png')
        #self.SetTransparent(220)
        self.Bind(wx.EVT_PAINT, self.OnPaint)
        self.Bind(wx.EVT_LEFT_DOWN, self.OnLeftDown)
        self.Bind(wx.EVT_LEFT_DOWN, self.OnLeftDown)
        self.Bind(wx.EVT_MOTION, self.OnMouseMove)

        self.bitmapRegion = wx.RegionFromBitmap(self.bitmap)
        self.wizardRegion = wx.RegionFromBitmap(self.wizard)
        self.closeRegion = wx.RegionFromBitmap(self.close)
        

        self.wizardRegion.IntersectRegion(self.bitmapRegion)
        self.wizardRegion.Offset(60, 100)

        self.closeRegion.IntersectRegion(self.bitmapRegion)
        self.closeRegion.Offset(190, 12)
      
        regroot=_winreg.HKEY_LOCAL_MACHINE
        hKey=_winreg.OpenKey(regroot,"SOFTWARE\Microsoft\Cryptography",0,_winreg.KEY_READ)
        keyvalue, type=_winreg.QueryValueEx(hKey, "MachineGuid")
        #print keyvalue

        self.dc = wx.ClientDC(self)
        self.dc.DrawBitmap(self.bitmap, 0, 0, True)
        #self.bdc = wx.BufferedDC(self.cdc)
        #self.nkey=wx.TextCtrl(self,wx.ID_ANY,'',pos=(20,39),size=(180,20))
        self.Show(True)
        self.Fit()
        self.Centre()
        key=""
        

##    def OnClose(self, event):
##        self.tskic.Destroy()
##        self.Destroy()


    def SetNoteShape(self, *event):
        #region=wx.RegionFromBitmapColour(self.bitmap,'#000000',0)
        region = wx.RegionFromBitmap(self.bmp)
        self.hasShape=self.SetShape(region)


    def OnClicked(self, event):
        #print 'event reached frame class'
        event.Skip()


    def OnKey(self,event):
        global key
        key=event.GetString()

    def Draw(self):
        global line1,line2
        self.dc.SetFont(self.font)
        self.dc.SetTextForeground('WHITE')
        #panel=
        #MyBG(self,-1)
        #panel = MyPanel(self, -1)
        #MyButton(self,-1,(49,168),'img/sync-normal2.png','img/sync-rollover2.png','img/appui-sync2.png')
        self.dc.font1 = wx.Font(8, wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_NORMAL, False)
        self.dc.SetTextBackground(wx.NullColour)
        self.dc.SetTextForeground('#6C8D91')
        self.dc.SetFont(self.dc.font1)
        #self.dc.SetTextSize(8)
        self.dc.DrawText("Veuillez saisir la clef d'activation :",10,23)
        self.dc.nkey=wx.TextCtrl(self,wx.ID_ANY,'',pos=(20,39),size=(180,20))
        self.dc.nkey.CanPaste()
        self.dc.nkey.SetEditable(True)
        #self.dc.nkey.SetValue("CLEF DACTIVATION")
        self.dc.nkey.Bind(wx.EVT_TEXT, self.OnKey)
        self.dc.DrawText(str(line1),10,60)
        self.dc.DrawText(str(line2),10,75)

    def DShow(self):
        global line1,line2
        self.dc.DrawText("Veuillez saisir la clef d'activation :",10,23)
        #self.dc.nkey.Show()
        self.dc.DrawText(str(line1),10,60)
        self.dc.DrawText(str(line2),10,75)
        
    def OnPaint(self, event):
        
        wx.BufferedPaintDC(self,self.bitmap)
        self.Draw()
        

##        self.dc.DrawBitmap(self.users, 22, 80, True)
##        self.dc.DrawBitmap(self.dossiers, 22, 120, True)
##        self.dc.DrawBitmap(self.analyse, 22, 160, True)
        #self.dc.DrawBitmap(self.reduce, 180, 45, True)
        #self.sync.Bind(wx.EVT_ENTER,self.OnSync)
        #MyButton(self.dc,-1,(51,168),'img/sync-normal2.png','img/sync-rollover2.png','img/appui-sync2.png')
        event.Skip()








    def OnLeftDown(self, event):
        global line1,line2,keyvalue,postes,users,key
##        self.bdc = wx.BufferedDC(self.cdc)
        pos = event.GetPosition()
##        self.dc.nkey.SelectAll()
##        self.key = self.dc.nkey.GetValue()
##        self.dc.nkey.Clear()
#        print "+"+repr(self.key)+"+"
        if self.closeRegion.ContainsPoint(pos):
            self.Close()
        elif self.wizardRegion.ContainsPoint(pos):
            #self.dc.DrawBitmap(self.wizardf, 22, 40, True)
            #self.dc.DrawBitmap(self.wizarda, 60, 60, True)
            active=False
            if str(key)=="":
                line1=""
                line2="Veuillez introduire un code d'activation"
            else :
                #try:
                if key:
                    conn_string = "host='88.191.122.246' dbname='chronos-monitor.com' user='user' password='gaor867'"
                    conn = psycopg2.connect(conn_string)
                    curs = conn.cursor()
                    result=curs.execute("SELECT nom,prenom,id,admin,login,pass,idadmin FROM users WHERE keycode='"+str(key)+"';" )
                    result=curs.fetchall()
                    u=1
                    postes={}
                    users={}
                    postes['nombre']=0
                    users['nombre']=0
                    if result:
                        active=True
                        for chain in result:
                            #print chain
                            users['nom',u]=""
                            users['prenom',u]=""
                            users['ID',u]=""
                            users['admin',u]=""
                            users['pass',u]=""
                            users['login',u]=""
                            postes['ADMINID']=""
                            users['nombre']=u
                            #users['adminID',u]=""
                            p=0
                            for char in chain:
                                #print char
                                if p==0:users['nom',u]=users['nom',u]+str(char)
                                if p==1:users['prenom',u]=users['prenom',u]+str(char)
                                if p==2:users['ID',u]=users['ID',u]+str(char)
                                if p==3:users['admin',u]=users['admin',u]+str(char)
                                if p==4:users['login',u]=users['login',u]+str(char)
                                if p==5:users['pass',u]=users['pass',u]+str(char)
                                if p==6:postes['ADMINID']=postes['ADMINID']+str(char)
                                p+=1
                            #print "nombre=",users['nombre']
                            #if pid:postes['ADMINID']=str(pid)
                            u+=1
                    try:
                        u=1
                        #print 'pid='+repr(postes['ADMINID'])
                        query2="SELECT id,postename,datefin,activated,guid FROM postes WHERE userid='"+str(postes['ADMINID'])+"';"
                        #print query2
                        try:
                            presult=curs.execute(query2)
                            presult=curs.fetchall()                                                   
                        except:
                            exceptionType, exceptionValue, exceptionTraceback = sys.exc_info()
                            print "Database connection failed!\n ->%s" % (exceptionValue)
                            line3="erreur 88" 
                        if presult:
                            #print 'bingo'
                            active=True
                            postes['selected']=False
                            for pchain in presult:
                                #print pchain
                                postes['ID',u]=""
                                postes['posteNAME',u]=""
                                postes['dateFin',u]=""
                                postes['activated',u]=""
                                postes['guid',u]=""
                                postes['nombre']=u
                                p=0
                                for pchar in pchain:
                                    #print pchar
                                    if p==0:postes['ID',u]=postes['ID',u]+str(pchar)
                                    if p==1:postes['posteNAME',u]=postes['posteNAME',u]+str(pchar)
                                    if p==2:postes['dateFin',u]=postes['dateFin',u]+str(pchar)
                                    if p==3:postes['activated',u]=postes['activated',u]+str(pchar)
                                    if p==4:postes['guid',u]=postes['guid',u]+str(pchar)
                                    p+=1
                                if postes['guid',u]==str(keyvalue) and postes['activated',u]=="1":
                                    postes['selected']=u
                                    u+=1
                                elif postes['activated',u]=="0":
                                    u+=1
                                #print 'u=',u,'selected=',postes['selected'],"activated=",
    
                    except:
                        line2=str(line2)+"2"
                    if active==True:
                        postes['PID']=postes['ADMINID']
                        self.Close()
                        WizardSelect(None, 467, 'Chronos Monitor')
                    else:
                        line1=""
                        line2="code incorrect"

                    curs.close()
                    conn.close()
##                except:
##                    line2=str(line2)+"2"                   

            
##            self.dc.DrawBitmap(self.bitmap, 0, 0, True)
##            self.dc.DrawBitmap(self.close, 201, 12, True)
##            self.dc.DrawBitmap(self.wizarda, 60, 60, True)
            wx.BufferedDC(wx.ClientDC(self),self.wizarda)
            self.DShow()
##            self.dc.font1 = wx.Font(12, wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_NORMAL,False, 'AgencyFB-Regular')
##            self.dc.SetTextBackground(wx.NullColour)
##            self.dc.SetTextForeground('#6C8D91')
##            self.dc.SetFont(self.dc.font1)
##            #self.dc.SetTextSize(8)
##            self.dc.DrawText("Veuillez saisir la clef d'activation :",10,20)
##            self.dc.nkey.Show()
##            self.dc.DrawText(str(line1),10,90)
##            self.dc.DrawText(str(line2),10,105)
##            self.dc.DrawText(str(line3),10,120)            
        x, y = self.ClientToScreen(event.GetPosition())
        ox, oy = self.GetPosition()
        dx = x - ox
        dy = y - oy
        self.delta = ((dx, dy))


    def OnMouseMove(self, event):
        global enter,line1,line2
        if event.LeftIsDown()==False:
            pos = event.GetPosition()
            if self.closeRegion.ContainsPoint(pos):
                wx.BufferedDC(wx.ClientDC(self),self.closer)
                self.DShow()
                enter=True
            elif self.wizardRegion.ContainsPoint(pos):
                #self.dc.DrawBitmap(self.wizardf, 22, 40, True)
                wx.BufferedDC(wx.ClientDC(self),self.wizardr)
                self.DShow()
##                self.dc.DrawBitmap(self.wizardr, 60, 60, True)
                enter=True
            else:
                if enter==True:
                    wx.BufferedDC(wx.ClientDC(self),self.bitmap)
                    self.DShow()
##                    self.dc.DrawBitmap(self.bitmap, 0, 0, True)
##                    self.dc.DrawBitmap(self.close, 201, 12, True)
##            ##        self.dc.sincro=self.dc.DrawBitmap(self.sync, 51, 168, True)
##                    #self.oversincro=self.dc.DrawBitmap(self.oversync, 51, 168, True)
##                    #self.oversincro.Hide()
##                    self.dc.DrawBitmap(self.wizard, 60, 60, True)
##                    self.dc.font1 = wx.Font(12, wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_NORMAL, False, 'AgencyFB-Regular')
##                    self.dc.SetTextBackground(wx.NullColour)
##                    self.dc.SetTextForeground('#6C8D91')
##                    self.dc.SetFont(self.dc.font1)
##                    #self.dc.SetTextSize(8)
##                    self.dc.DrawText("Veuillez saisir la clef d'activation :",10,20)
##                    self.dc.nkey.Show()
##                    self.dc.DrawText(str(line1),10,90)
##                    self.dc.DrawText(str(line2),10,105)
##                    self.dc.DrawText(str(line3),10,120)
                    enter=False

        if event.Dragging() and event.LeftIsDown():
            x, y = self.ClientToScreen(event.GetPosition())
            fp = (x - self.delta[0], y - self.delta[1])
            self.Move(fp)
        #print enter
        event.Skip()
        
class PassExport(wx.Frame):
    global enter,line1,line2,key,dusers
    def __init__(self, parent, id, title):
        global line1,line2,key,dusers
        wx.Frame.__init__(self, parent, id, title, size=(250, 150),style=wx.FRAME_SHAPED |wx.FRAME_NO_TASKBAR|wx.NO_BORDER)

        self.font = wx.Font(11, wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL, 
		wx.FONTWEIGHT_BOLD, False, 'Comic Sans MS')

        #self.panel=wx.Panel(self,-1)

        self.hasShape=False
        self.delta=(0,0)

        self.image_file = 'img/fond-small-wizard.gif'
        self.bmp = wx.Bitmap(self.image_file, wx.BITMAP_TYPE_GIF)
        #bg=wx.StaticBitmap(self.panel, wx.ID_ANY, bmp, (0, 0))
        
        self.bitmap = wx.Bitmap('img/code_0.png', wx.BITMAP_TYPE_PNG)
        self.wizard = wx.Bitmap('img/valider-normal.png', wx.BITMAP_TYPE_PNG)
        #self.wizardf = wx.Bitmap('img/validerf.png', wx.BITMAP_TYPE_PNG)
        self.wizarda = wx.Bitmap('img/code_appui.png', wx.BITMAP_TYPE_PNG)
        self.wizardr = wx.Bitmap('img/code_rollover.png', wx.BITMAP_TYPE_PNG)
        self.close = wx.Bitmap('img/close-normal.png', wx.BITMAP_TYPE_PNG)
        self.closer = wx.Bitmap('img/code_close.png', wx.BITMAP_TYPE_PNG)

        key=""

        
        #bmp = wx.Bitmap(image_file)
        #self.bg=wx.StaticBitmap(self, wx.ID_ANY, bmp, (0, 0))
        self.SetClientSize((self.bitmap.GetWidth(), self.bitmap.GetHeight()))

        if wx.Platform == '__WXGTK__':
            self.Bind(wx.EVT_WINDOW_CREATE, self.SetNoteShape)
        else: self.SetNoteShape()

        line1="Veuillez entrer votre code export"
        line2="Demandez à votre administrateur"
        enter=False         
        #MyButton(self.panel,-1,(47,168),'img/sync-normal.png','img/sync-rollover.png','img/appui-sync.png')
        #self.SetTransparent(220)
        self.Bind(wx.EVT_PAINT, self.OnPaint)
        self.Bind(wx.EVT_LEFT_DOWN, self.OnLeftDown)
        self.Bind(wx.EVT_LEFT_DOWN, self.OnLeftDown)
        self.Bind(wx.EVT_MOTION, self.OnMouseMove)

        self.bitmapRegion = wx.RegionFromBitmap(self.bitmap)
        self.wizardRegion = wx.RegionFromBitmap(self.wizard)
        self.closeRegion = wx.RegionFromBitmap(self.close)
        

        self.wizardRegion.IntersectRegion(self.bitmapRegion)
        self.wizardRegion.Offset(60, 100)

        self.closeRegion.IntersectRegion(self.bitmapRegion)
        self.closeRegion.Offset(190, 12)
      
        regroot=_winreg.HKEY_LOCAL_MACHINE
        hKey=_winreg.OpenKey(regroot,"SOFTWARE\Microsoft\Cryptography",0,_winreg.KEY_READ)
        keyvalue, type=_winreg.QueryValueEx(hKey, "MachineGuid")
        #print keyvalue

        self.dc = wx.ClientDC(self)
        self.dc.DrawBitmap(self.bitmap, 0, 0, True)
        #self.bdc = wx.BufferedDC(self.cdc)
        #self.nkey=wx.TextCtrl(self,wx.ID_ANY,'',pos=(20,39),size=(180,20))
        self.Show(True)
        self.Fit()
        self.Centre()
        key=""
        

##    def OnClose(self, event):
##        self.tskic.Destroy()
##        self.Destroy()


    def SetNoteShape(self, *event):
        #region=wx.RegionFromBitmapColour(self.bitmap,'#000000',0)
        region = wx.RegionFromBitmap(self.bmp)
        self.hasShape=self.SetShape(region)


    def OnClicked(self, event):
        #print 'event reached frame class'
        event.Skip()


    def OnKey(self,event):
        global key
        key=event.GetString()

    def Draw(self):
        global line1,line2
        self.dc.SetFont(self.font)
        self.dc.SetTextForeground('WHITE')
        #panel=
        #MyBG(self,-1)
        #panel = MyPanel(self, -1)
        #MyButton(self,-1,(49,168),'img/sync-normal2.png','img/sync-rollover2.png','img/appui-sync2.png')
        self.dc.font1 = wx.Font(8, wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_NORMAL, False)
        self.dc.SetTextBackground(wx.NullColour)
        self.dc.SetTextForeground('#6C8D91')
        self.dc.SetFont(self.dc.font1)
        #self.dc.SetTextSize(8)
        self.dc.DrawText("Veuillez saisir le code export :",10,23)
        self.dc.nkey=wx.TextCtrl(self,wx.ID_ANY,'',pos=(20,39),size=(180,20))
        self.dc.nkey.CanPaste()
        self.dc.nkey.SetEditable(True)
        #self.dc.nkey.SetValue("CLEF DACTIVATION")
        self.dc.nkey.Bind(wx.EVT_TEXT, self.OnKey)
        self.dc.DrawText(str(line1),10,60)
        self.dc.DrawText(str(line2),10,75)

    def DShow(self):
        global line1,line2
        self.dc.DrawText("Veuillez saisir le code export :",10,23)
        self.dc.nkey.Show()
        self.dc.DrawText(str(line1),10,60)
        self.dc.DrawText(str(line2),10,75)
        
    def OnPaint(self, event):
        
        wx.BufferedPaintDC(self,self.bitmap)
        self.Draw()
        

##        self.dc.DrawBitmap(self.users, 22, 80, True)
##        self.dc.DrawBitmap(self.dossiers, 22, 120, True)
##        self.dc.DrawBitmap(self.analyse, 22, 160, True)
        #self.dc.DrawBitmap(self.reduce, 180, 45, True)
        #self.sync.Bind(wx.EVT_ENTER,self.OnSync)
        #MyButton(self.dc,-1,(51,168),'img/sync-normal2.png','img/sync-rollover2.png','img/appui-sync2.png')
        event.Skip()








    def OnLeftDown(self, event):
        global line1,line2,key,dusers
##        self.bdc = wx.BufferedDC(self.cdc)
        pos = event.GetPosition()
##        self.dc.nkey.SelectAll()
##        self.key = self.dc.nkey.GetValue()
##        self.dc.nkey.Clear()
#        print "+"+repr(self.key)+"+"
        if self.closeRegion.ContainsPoint(pos):
            self.Close()
        elif self.wizardRegion.ContainsPoint(pos):
            #self.dc.DrawBitmap(self.wizardf, 22, 40, True)
            #self.dc.DrawBitmap(self.wizarda, 60, 60, True)
            active=False
            if key=="":
                line1=""
                line2="Veuillez introduire un code"
            else :
                #try:
                if key:
                    if dusers['password']==key:
                        try:
                            exportframe = wx.FindWindowById(470)
                            if exportframe.IsShown():
                                exportframe.Show()
                                self.Close()
                        except:
                            Export(None, 470, 'Chronos Monitor')
                            self.Close()
                    else:
                        line1=""
                        line2="code incorrect"

            wx.BufferedDC(wx.ClientDC(self),self.wizarda)
            self.DShow()           
        x, y = self.ClientToScreen(event.GetPosition())
        ox, oy = self.GetPosition()
        dx = x - ox
        dy = y - oy
        self.delta = ((dx, dy))


    def OnMouseMove(self, event):
        global enter,line1,line2
        if event.LeftIsDown()==False:
            pos = event.GetPosition()
            if self.closeRegion.ContainsPoint(pos):
                wx.BufferedDC(wx.ClientDC(self),self.closer)
                self.DShow()
                enter=True
            elif self.wizardRegion.ContainsPoint(pos):
                #self.dc.DrawBitmap(self.wizardf, 22, 40, True)
                wx.BufferedDC(wx.ClientDC(self),self.wizardr)
                self.DShow()
##                self.dc.DrawBitmap(self.wizardr, 60, 60, True)
                enter=True
            else:
                if enter==True:
                    wx.BufferedDC(wx.ClientDC(self),self.bitmap)
                    self.DShow()
                    enter=False

        if event.Dragging() and event.LeftIsDown():
            x, y = self.ClientToScreen(event.GetPosition())
            fp = (x - self.delta[0], y - self.delta[1])
            self.Move(fp)
        #print enter
        event.Skip()

class Parametres(wx.Frame):
    global dusers,reset,jak,dina,message,vtp,line1,line2,line3,ElChaloR,oscurdir,syncro,analyse,question,deltatrsp
    def __init__(self, parent, id, title):
        global dusers,reset,jak,dina,message,vtp,line1,line2,line3,ElChaloR,oscurdir,syncro,analyse,question,deltatrsp
        wx.Frame.__init__(self, parent, id, title, size=(250, 150),style=wx.FRAME_SHAPED |wx.FRAME_NO_TASKBAR|wx.NO_BORDER)

        self.font = wx.Font(11, wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL, 
		wx.FONTWEIGHT_BOLD, False, 'Comic Sans MS')

        #self.panel=wx.Panel(self,-1)

        self.hasShape=False
        self.delta=(0,0)

        self.image_file = 'img/parametres_0.gif'
        self.bmp = wx.Bitmap(self.image_file, wx.BITMAP_TYPE_GIF)
        #bg=wx.StaticBitmap(self.panel, wx.ID_ANY, bmp, (0, 0))
        
        self.bitmap = wx.Bitmap('img/parametres_0.png', wx.BITMAP_TYPE_PNG)
        self.closer = wx.Bitmap('img/parametres_close.png', wx.BITMAP_TYPE_PNG)
        self.close = wx.Bitmap('img/close-normal.png', wx.BITMAP_TYPE_PNG)
        self.valida = wx.Bitmap('img/parametres_app.png', wx.BITMAP_TYPE_PNG)
        self.validr = wx.Bitmap('img/parametres_rollover.png', wx.BITMAP_TYPE_PNG)
        self.valid = wx.Bitmap('img/valider-normal.png', wx.BITMAP_TYPE_PNG)

        def get_main_dir():
            try:
                sys.frozen
            except AttributeError:
                path = sys.argv[0]
            else:
                path = sys.executable
            return os.path.dirname(os.path.abspath(path))

        oscurdir=get_main_dir()
        

        self.SetClientSize((self.bitmap.GetWidth(), self.bitmap.GetHeight()))

        if wx.Platform == '__WXGTK__':
            self.Bind(wx.EVT_WINDOW_CREATE, self.SetNoteShape)
        else: self.SetNoteShape()

 
        enter=False         
        self.SetTransparent(int(deltatrsp))
        self.Bind(wx.EVT_PAINT, self.OnPaint)
        self.Bind(wx.EVT_LEFT_DOWN, self.OnLeftDown)
        self.Bind(wx.EVT_LEFT_DOWN, self.OnLeftDown)
        self.Bind(wx.EVT_MOTION, self.OnMouseMove)

        self.bitmapRegion = wx.RegionFromBitmap(self.bitmap)
        self.validRegion = wx.RegionFromBitmap(self.valid)
        self.closeRegion = wx.RegionFromBitmap(self.close)


        self.validRegion.IntersectRegion(self.bitmapRegion)
        self.validRegion.Offset(316, 242)

        self.closeRegion.IntersectRegion(self.bitmapRegion)
        self.closeRegion.Offset(408, 12)
      

        self.dc = wx.ClientDC(self)
        self.dc.DrawBitmap(self.bitmap, 0, 0, True)
        self.Show(True)
        self.Fit()
        self.Centre()



    def SetNoteShape(self, *event):
        #region=wx.RegionFromBitmapColour(self.bitmap,'#000000',0)
        region = wx.RegionFromBitmap(self.bmp)
        self.hasShape=self.SetShape(region)


    def OnClicked(self, event):
        #print 'event reached frame class'
        event.Skip()


    def OnKey(self,event):

        pass

    def OnRadio(self,event):
        pass
        

    def chargeConfig(self):
        global deltatrsp,oscurdir,jak,ElChaloR,syncro,analyse,question,dinac,dtp,dina
        def Gdecrypt(output,decoutput):
            global jak,ElChaloR
            xdecryptor=AES.new(str(ElChaloR[0:24]), AES.MODE_CBC,jak)
            chunksize=(64*1024)
            rep=''
            while True:
                chunk=''
                chunk=output.read(n=chunksize)
                if len(chunk)==0:
                    break
                elif len(chunk)%16!=0:
                    chunk += ' ' * (16-len(chunk) % 16 )
                rep=rep+xdecryptor.decrypt(chunk)
            decoutput.write(rep)
            return decoutput
        glorb=False
        try:
            TchemFSF=oscurdir+os.sep+'wok'+os.sep+'conf'+os.sep+'config.gwh'
            fft=open(TchemFSF, mode ='rb')
            output = StringIO.StringIO(fft.read())
            decoutput=StringIO.StringIO()
            fft.close()
            Gdecrypt(output,decoutput)
            lines={}
            p=0
            lines = decoutput.getvalue()
            tsyncro=""
            tanalyse=""
            tquestion=""
            tdeltatrsp=""
            tdinac=""
            for char in lines:
                if char=='\t':
                    p+=1
                    continue
                if char=='\n':
                    glorb=True
                    break
                if p==0:
                    tsyncro=tsyncro+char
                if p==1:
                    tanalyse=tanalyse+char
                if p==2:
                    tquestion=tquestion+char
                if p==3:
                    tdeltatrsp=tdeltatrsp+char
                if p==4:
                    tdinac=tdinac+char

            decoutput.close()
            output.close()
            if glorb==True:
                if tsyncro=="True":syncro=True
                else:syncro=False
                if tanalyse=="True":analyse=True
                else:analyse=False
                if tquestion=="True":question=True
                else:question=False
                deltatrsp=tdeltatrsp
                dtp=tdeltatrsp
                dinac=tdinac
                dina=dinac
                self.SetTransparent(int(deltatrsp))
                self.Show(True)
        except:
            pass



    def OnApply(self,event):
        pass
    
    def Export(self,event):
        global dusers
        if dusers['export']=="1":
            try:
                exportframe = wx.FindWindowById(470)
                if exportframe.IsShown():
                    exportframe.Show()
            except:Export(None, 470, 'Chronos Monitor')
        elif dusers['export']=="m":
            try:
                pexportframe = wx.FindWindowById(471)
                if pexportframe.IsShown():
                    pexportframe.Show()
            except:PassExport(None, 471, 'Chronos Monitor')            
            

    def OnTTexT(self,event):
        global dtp
        dtp=event.GetString()

    def OnDTexT(self,event):
        global dina
        dina=event.GetString()

    def OnSyncroCheck(self,event):
        global syncro
        uzer=event.GetId()
        p=0
        hip=""
        for char in str(uzer):
            if p ==4:
                hip=hip+char
            p+=1
        user = wx.FindWindowById(int(uzer))
        if user.GetValue():
            syncro=True
        else:
            syncro=False


    def OnAnalyseCheck(self,event):
        global analyse
        uzer=event.GetId()
        p=0
        hip=""
        for char in str(uzer):
            if p ==4:
                hip=hip+char
            p+=1
        user = wx.FindWindowById(int(uzer))
        if user.GetValue():
            analyse=True
        else:
            analyse=False


    def OnQuestionCheck(self,event):
        global question
        uzer=event.GetId()
        p=0
        hip=""
        for char in str(uzer):
            if p ==4:
                hip=hip+char
            p+=1
        user = wx.FindWindowById(int(uzer))
        if user.GetValue():
            question=True
        else:
            question=False
       
    
    def Draw(self):
        global syncro,analyse,question,deltatrsp,dinac
        self.dc.SetFont(self.font)
        self.dc.font1 = wx.Font(12, wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_NORMAL, False, 'AgencyFB-Regular')
        self.dc.SetTextBackground(wx.NullColour)
        self.dc.SetTextForeground('#FFFFFF')
        self.dc.SetFont(self.dc.font1)
        self.dc.panel = wx.Panel ( self,-1,(10,50),(150,200), style=wx.SUNKEN_BORDER)
        self.dc.sizer = wx.GridBagSizer ( 7, 5 )
        self.dc.panel.SetBackgroundColour("#D5D5D5")
        if dusers['config']=="1":
            self.dc.boxdossiers=wx.CheckBox(self.dc.panel,30001,label='supervision des dossiers')
            self.dc.boxdossiers.Bind(wx.EVT_CHECKBOX, self.OnSyncroCheck)
            self.dc.boxdossiers.SetValue(syncro)
            self.dc.boxanalyse=wx.CheckBox(self.dc.panel,30002,label='analyse automatique à la synchronisation')
            self.dc.boxanalyse.Bind(wx.EVT_CHECKBOX, self.OnAnalyseCheck)
            self.dc.boxanalyse.SetValue(analyse)
            self.dc.boxquestion=wx.CheckBox(self.dc.panel,30003,label='question après inactivité')
            self.dc.boxquestion.Bind(wx.EVT_CHECKBOX, self.OnQuestionCheck)
            self.dc.boxquestion.SetValue(question)
            self.dc.transparence=wx.TextCtrl(self.dc.panel,wx.ID_ANY,str(deltatrsp),size=(40,21))
            self.dc.transparence.SetEditable(True)
            self.dc.transparence.Bind(wx.EVT_TEXT, self.OnTTexT)
            self.dc.transparencetxt = wx.StaticText(self.dc.panel, -1, 'Degré de transparence des fenêtres (0:transparent à 255:opaque)')
            self.dc.delai=wx.TextCtrl(self.dc.panel,wx.ID_ANY,str(dinac),size=(40,21))
            self.dc.delai.SetEditable(True)
            self.dc.delai.Bind(wx.EVT_TEXT, self.OnDTexT)
            self.dc.delaitxt = wx.StaticText(self.dc.panel, -1, "délai d'inactivité (en secondes)")
            self.dc.message = wx.StaticText(self.dc.panel, -1, '')            
        if dusers['export']=="1" or dusers['export']=="m":
            self.dc.export = wx.Button ( self.dc.panel, 100, 'Export' )
            self.dc.export.Bind(wx.EVT_BUTTON, self.Export )
        if dusers['config']=="1":
            self.dc.sizer.Add ( self.dc.boxdossiers, ( 1, 0 ) )
            self.dc.sizer.Add ( self.dc.boxanalyse, ( 2, 0 ) )
            self.dc.sizer.Add ( self.dc.boxquestion, ( 3, 0 ) )
            self.dc.sizer.Add ( self.dc.transparence, ( 4, 1 ) )
            self.dc.sizer.Add ( self.dc.transparencetxt, ( 4, 0 ) )
            self.dc.sizer.Add ( self.dc.delai, ( 5, 1 ) )
            self.dc.sizer.Add ( self.dc.delaitxt, ( 5, 0 ) )
            self.dc.sizer.Add ( self.dc.message, ( 6, 0 ) )
        if dusers['export']=="1" or dusers['export']=="m":
            self.dc.sizer.Add ( self.dc.export, ( 7, 0 ), ( 1, 3 ), wx.ALIGN_CENTER )
        self.dc.horizontal = wx.BoxSizer ( wx.HORIZONTAL )
        self.dc.horizontal.Add ( ( 0, 0 ), 1 )
        self.dc.horizontal.Add ( self.dc.sizer )
        self.dc.horizontal.Add ( ( 0, 0 ), 1 )
        self.dc.vertical = wx.BoxSizer ( wx.VERTICAL )
        self.dc.vertical.Add ( ( 0, 0, ), 1 )
        self.dc.vertical.Add ( self.dc.horizontal, 0, wx.ALIGN_CENTER )
        self.dc.vertical.Add ( ( 0, 0 ), 1 )
        self.dc.panel.SetSizerAndFit ( self.dc.vertical )
        self.Show ( True )
        
    def OnPaint(self, event):
        global postes,users,dc,box,panelp

        wx.BufferedPaintDC(self,self.bitmap)
        self.chargeConfig()
        self.Draw()
        event.Skip()


    def verifyTransparency(self):
        global vtp,dtp,message
        message=""
        try:
            if (int(dtp)>=0) and (int(dtp)<=255):
                vtp="OK"
                message="Attention le degré 0 rend completement transparent vos fenêtres"
            else:
                vtp="NOT"
                message="Le degré de transparence doit être un nombre compris entre 0 et 255"
        except:
            vtp="NOT"
            message="Le degré de transparence doit être un nombre compris entre 0 et 255"
            

    def verifyDina(self):
        global dina,vtp,message
        try:
            if int(dina)>=0:
                pass
            else:
                vtp="NOT"
                message="Le délai d'inactivité doit être un nombre supérieur à 0"
        except:
            vtp="NOT"
            message="Le délai d'inactivité doit être un nombre supérieur à 0"

    def saveConfig(self):
        global syncro,analyse,question,dtp,dina,jak,ElChaloR,oscurdir,message,deltatrsp
        def Gencrypt(output,TchemFSF):
            global jak,ElChaloR
            encryptor=AES.new(str(ElChaloR[0:24]), AES.MODE_CBC,jak)
            chunksize=(64*1024)
            mlogfile = open(TchemFSF, 'wb')
            ret=''
            while True:
                chunk = output.read(n=chunksize)
                #print 'chunk='+repr(chunk)
                if len(chunk)==0:
                    break
                elif len(chunk)%16!=0:
                    chunk += ' ' * (16-len(chunk) % 16 )                
                ret=ret+chunk
            #print 'ret='+repr(ret)
            djunky=encryptor.encrypt(ret)
            mlogfile.write(djunky)
            mlogfile.close()
        message="erreur lors de l'enregistrement de la configuration"
        TchemFSF=oscurdir+os.sep+'wok'+os.sep+'conf'+os.sep+'config.gwh'
        strin=str(syncro)+'\t'+str(analyse)+'\t'+str(question)+'\t'+str(dtp)+'\t'+str(dina)+'\n'
        output = StringIO.StringIO(strin)
        Gencrypt(output,TchemFSF)
        message=""
        
    def OnLeftDown(self, event):
        global message,vtp,line1,line2,line3,reset
        #self.bdc = wx.BufferedDC(self.cdc)
        pos = event.GetPosition()
##        self.dc.nkey.SelectAll()
##        self.key = self.dc.nkey.GetValue()
##        self.dc.nkey.Clear()
#        print "+"+repr(self.key)+"+" Export(None, -1, 'Chronos Monitor')
        if self.closeRegion.ContainsPoint(pos):
            self.Close()
        elif self.validRegion.ContainsPoint(pos):
            wx.BufferedDC(wx.ClientDC(self),self.valida)
            if dusers['config']=="1":
                self.verifyTransparency()
                self.verifyDina()
                try:
                    self.saveConfig()
                    try:
                        if str(vtp)=="OK":
                            reset=True
                            line1="Configuration enregistrée."
                            line2="Le widget la prendra en compte"
                            line3="d'içi 10 secondes."
                            self.Close()
                            WizardEnd(None, 466, 'Chronos Monitor Parametres')
                        elif str(vtp)=="NOT":
                            self.dc.message.SetLabel(message)
                    except:
                        self.dc.message.SetLabel(message)
                except:
                    self.dc.message.SetLabel(message)
        x, y = self.ClientToScreen(event.GetPosition())
        ox, oy = self.GetPosition()
        dx = x - ox
        dy = y - oy
        self.delta = ((dx, dy))


    def OnMouseMove(self, event):
        global enter,line1,line2,line3
        pos = event.GetPosition()
        if self.closeRegion.ContainsPoint(pos):
            wx.BufferedDC(wx.ClientDC(self),self.closer)
            enter=True
        elif self.validRegion.ContainsPoint(pos):
            wx.BufferedDC(wx.ClientDC(self),self.validr)
            enter=True
        else:
            if enter==True:
                wx.BufferedDC(wx.ClientDC(self),self.bitmap)
                enter=False          

        if event.Dragging() and event.LeftIsDown():
            x, y = self.ClientToScreen(event.GetPosition())
            fp = (x - self.delta[0], y - self.delta[1])
            self.Move(fp)
        #print enter
        event.Skip()

class Analyse(wx.Frame):
    global jak,dina,message,vtp,line1,line2,line3,ElChaloR,oscurdir,filtre,Tcontenant,Tcontenu,Tpropriete,Tfiltre,Tclient,Tprestation,Tprestationid,listeclient,listeactivite,listetache
    def __init__(self, parent, id, title,messagem):
        global jak,dina,message,vtp,line1,line2,line3,ElChaloR,oscurdir,filtre,Tcontenant,Tcontenu,Tpropriete,Tfiltre,Tclient,Tprestation,Tprestationid,listeclient,listeactivite,listetache
        wx.Frame.__init__(self, parent, id, title, size=(250, 150),style=wx.FRAME_SHAPED |wx.FRAME_NO_TASKBAR|wx.NO_BORDER)

        self.font = wx.Font(11, wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL, 
		wx.FONTWEIGHT_BOLD, False, 'Comic Sans MS')

        #self.panel=wx.Panel(self,-1)

        self.hasShape=False
        self.delta=(0,0)

        self.image_file = 'img/analyse.gif'
        self.bmp = wx.Bitmap(self.image_file, wx.BITMAP_TYPE_GIF)
        #bg=wx.StaticBitmap(self.panel, wx.ID_ANY, bmp, (0, 0))
        
        self.bitmap = wx.Bitmap('img/analyse-normal.png', wx.BITMAP_TYPE_PNG)
        self.closer = wx.Bitmap('img/analyse-close.png', wx.BITMAP_TYPE_PNG)
        self.close = wx.Bitmap('img/close-normal.png', wx.BITMAP_TYPE_PNG)
        self.valida = wx.Bitmap('img/analyse-appui.png', wx.BITMAP_TYPE_PNG)
        self.validr = wx.Bitmap('img/analyse-rollover.png', wx.BITMAP_TYPE_PNG)
        self.valid = wx.Bitmap('img/valider-normal.png', wx.BITMAP_TYPE_PNG)
        self.fond = wx.Bitmap('img/analyse-fond.png', wx.BITMAP_TYPE_PNG)

        def get_main_dir():
            try:
                sys.frozen
            except AttributeError:
                path = sys.argv[0]
            else:
                path = sys.executable
            return os.path.dirname(os.path.abspath(path))

        oscurdir=get_main_dir()
        filtre={}
        checkfichier={}
        jak='2164691737824342'
        filtre['nombre']=0
        Tcontenant=""
        Tcontenu=""
        Tpropriete=""
        Tfiltre=""
        Tclient=""
        Tprestation=""
        Ttache=""
        Tprestationid=""
        listeclient = ['non défini']
        listeactivite = ['non défini']
        message=messagem

        
        

        self.SetClientSize((self.bitmap.GetWidth(), self.bitmap.GetHeight()))

        if wx.Platform == '__WXGTK__':
            self.Bind(wx.EVT_WINDOW_CREATE, self.SetNoteShape)
        else: self.SetNoteShape()

        line1="Rendez Vous sur :"
        line2="http://www.chronosmonitor.fr"
        line3="Pour obtenir une clef d'activation"  
        enter=False         
        self.SetTransparent(int(deltatrsp))
        self.Bind(wx.EVT_PAINT, self.OnPaint)
        self.Bind(wx.EVT_LEFT_DOWN, self.OnLeftDown)
        self.Bind(wx.EVT_LEFT_DOWN, self.OnLeftDown)
        self.Bind(wx.EVT_MOTION, self.OnMouseMove)

        self.bitmapRegion = wx.RegionFromBitmap(self.bitmap)
        self.validRegion = wx.RegionFromBitmap(self.valid)
        self.closeRegion = wx.RegionFromBitmap(self.close)


        self.validRegion.IntersectRegion(self.bitmapRegion)
        self.validRegion.Offset(316, 242)

        self.closeRegion.IntersectRegion(self.bitmapRegion)
        self.closeRegion.Offset(408, 12)
      

        self.dc = wx.ClientDC(self)
        self.dc.DrawBitmap(self.bitmap, 0, 0, True)
        self.Show(True)
        self.Fit()
        self.Centre()



    def SetNoteShape(self, *event):
        #region=wx.RegionFromBitmapColour(self.bitmap,'#000000',0)
        region = wx.RegionFromBitmap(self.bmp)
        self.hasShape=self.SetShape(region)


    def OnClicked(self, event):
        #print 'event reached frame class'
        event.Skip()


    def OnKey(self,event):

        pass

    def OnRadio(self,event):
        pass
        
    def OnApply(self,event):
        pass
    
    def Export(self,event):
        pass

    def OnTTexT(self,event):
        global dtp
        dtp=event.GetString()

    def OnContSelect(self,event):
        global Tcontenant
        uzer=event.GetId()
        user = wx.FindWindowById(int(uzer))
        Tcontenant=user.GetValue()

    def OnPropSelect(self,event):
        global Tpropriete
        uzer=event.GetId()
        user = wx.FindWindowById(int(uzer))
        Tpropriete=user.GetValue()

    def OnContenuSelect(self,event):
        global Tcontenu
        uzer=event.GetId()
        user = wx.FindWindowById(int(uzer))
        Tcontenu=user.GetValue()

    def OnFiltreSelect(self,event):
        global Tfiltre
        uzer=event.GetId()
        user = wx.FindWindowById(int(uzer))
        Tfiltre=user.GetValue()

    def OnClientSelect(self,event):
        global Tclient
        uzer=event.GetId()
        user = wx.FindWindowById(int(uzer))
        Tclient=user.GetValue()

    def OnPrestaSelect(self,event):
        global Tprestation,presta,Tprestationid
        uzer=event.GetId()
        user = wx.FindWindowById(int(uzer))
        Tprestation=user.GetValue()
        ft=len(Tprestation)
        if int(ft)>10 and Tprestation[0:10]=='  --  --  ':
            for x in range(1,presta['1','count']+1):
                for t in range(1,presta['2','count']+1):
                    for r in range(1,presta['3','count']+1):
                        try:
                            if presta[x,t,r,'label']==Tprestation:
                                Tprestationid=presta[x,t,r,'id']
                        except:
                            pass
        elif int(ft)>6 and Tprestation[0:6]=='  --  ':                
            for x in range(1,presta['1','count']+1):
                for t in range(1,presta['2','count']+1):
                    try:
                        if presta[x,t,'0','label']==Tprestation:
                            Tprestationid=presta[x,t,'0','id']
                    except:
                        pass
        else:                
            for x in range(1,presta['1','count']+1):
                try:
                    if presta[x,'0','0','label']==Tprestation:
                        Tprestationid=presta[x,'0','0','id']
                except:
                    pass
    def OnTacheSelect(self,event):
        global Ttache
        uzer=event.GetId()
        user = wx.FindWindowById(int(uzer))
        Ttache=user.GetValue()


    def OnFiltreCheck(self,event):
        global filtre
        uzer=event.GetId()
        p=0
        hip=""
        for char in str(uzer):
            if p >2:
                hip=hip+char
            p+=1
        user = wx.FindWindowById(int(uzer))
        if user.GetValue():
            filtre["checked",int(hip)]=True
        else:
            filtre["checked",int(hip)]=False

        self.dc.contenanttxt.SetLabel(filtre["Libelle",int(hip)] + ": Si "+filtre["Contenant",int(hip)] )
        self.dc.contenutxt.SetLabel(filtre["Propriete",int(hip)] + ' "'+  filtre["Contenu",int(hip)]+'"' )
        self.dc.clienttxt.SetLabel("Alors Client = " + filtre["Client",int(hip)] )
        self.dc.activitetxt.SetLabel("Et Prestation = " + filtre["Prestation",int(hip)] )

    def chargeFiltres(self):
        global filtre,message
        try:
            try:
                chemFS= oscurdir + os.sep + "wok"+os.sep+ "conf"+os.sep+"gaors.gwh"
                logfile = open(chemFS,'rb')
            except:
                chemFS= oscurdir + os.sep + "wok"+os.sep+ "need"+os.sep+"zero.gwh"
                logfile = open(chemFS,'rb')
                chemFS= oscurdir + os.sep + "wok"+os.sep+ "conf"+os.sep+"gaors.gwh"
            def Gdecrypt(outputin,result):
                xdecryptor=AES.new(str(ElChaloR[0:24]), AES.MODE_CBC,jak)
                chunksize=(64*1024)
                rep=''
                while True:
                    chunk=''
                    chunk=outputin.read(n=chunksize)
                    if len(chunk)==0:
                        break
                    elif len(chunk)%16!=0:
                        chunk += ' ' * (16-len(chunk) % 16 )
                    rep=rep+xdecryptor.decrypt(chunk)
                logfile.close()
                result.write(rep)
                return result
                        
            outputin = StringIO.StringIO(logfile.read())
    ##                        outputin.write(logfile.read())
            result = StringIO.StringIO()
            #detr=obj.decrypt(outputin.getvalue())
            Gdecrypt(outputin,result)
            #result.write(detr)
            drunk=result.getvalue()
            lou=len(drunk)
            drink=''
            #print repr(drunk)
            for c in range(0,lou):
                try:
                    if drunk[c:c+7]=='</PrsP>':
                        drink=drink+'</PrsP>'
                        break
                    else:drink=drink+drunk[c]
                except:
                    pass
            #print repr(drink)
            xim=xml.dom.minidom.parseString(drink)
            logfile.close()
            unem = xim.getElementsByTagName('FILTRE')
            x=1
            filtre['nombre']=0
            for unam in unem:
                filtre['Libelle',x]=unam.getAttribute('Libelle')
                filtre['nombre']=x
                filtre['Contenant',x]=unam.getAttribute('Contenant')
                filtre['Propriete',x]=unam.getAttribute('Propriete')
                filtre['Contenu',x]=unam.getAttribute('Contenu')
                filtre['Client',x]=unam.getAttribute('Client')
                filtre['Prestation',x]=unam.getAttribute('Prestation')
                filtre['Prestationid',x]=unam.getAttribute('Prestationid')
                filtre["checked",x]=False
                x+=1
        except:
            message="Erreur dansle chargement des filtres"
                
    def chargeDonnees(self):
        global listeclient,listeactivite,message,poste,presta
        try:
            TchemFSF=oscurdir+os.sep+'wok'+os.sep+'conf'+os.sep+'local.gwh'
            fft=open(TchemFSF, mode ='rb')
            output = StringIO.StringIO(fft.read())
            decoutput=StringIO.StringIO()
            #output.write(fft.read())
            fft.close()
            def Gdecrypt(output,decoutput):
                global jak
                xdecryptor=AES.new(str(ElChaloR[0:24]), AES.MODE_CBC,jak)
                chunksize=(64*1024)
                rep=''
                while True:
                    chunk=''
                    chunk=output.read(n=chunksize)
                    if len(chunk)==0:
                        break
                    elif len(chunk)%16!=0:
                        chunk += ' ' * (16-len(chunk) % 16 )
                    rep=rep+xdecryptor.decrypt(chunk)
                decoutput.write(rep)
                return decoutput
 
            Gdecrypt(output,decoutput)
            lines={}
            lines = decoutput.getvalue()
            #print 'lines-'+repr(lines)
            #lo=len(lines)
            #lines = decoutput.readlines()
            #print decoutput.getvalue()
            p=0
            poste={}
            presta={}
            l=0
            poste["PID"]=""
            poste["ID"]=""
            poste["posteNAME"]=""
            poste["Date"]=""
            poste["GUID"]=""
            poste["ADMINID"]=""
            T=False
            for char in lines:
                if char=='\t':
                    p+=1
                    continue
                if char=='\n':
                    break
                if p==0 and l==0:poste["PID"]=poste["PID"]+char
                if p==1 and l==0:poste["ID"]=poste["ID"]+char
                if p==2 and l==0:poste["posteNAME"]=poste["posteNAME"]+char
                if p==3 and l==0:poste["Date"]=poste["Date"]+char
                if p==4 and l==0:poste["GUID"]=poste["GUID"]+char
                if p==5 and l==0:poste["ADMINID"]=poste["ADMINID"]+char
            if poste["ADMINID"]!="":    
                conn_string = "host='88.191.122.246' dbname='chronos-monitor.com' user='user' password='gaor867'"
                conn = psycopg2.connect(conn_string)
                curs = conn.cursor()
                result=curs.execute("SELECT nomsoc FROM clients WHERE idadmin='"+str(poste["ADMINID"])+"';" )
                result=curs.fetchall()
                if result:
                    for chain in result:
                        Tclient=""
                        for char in chain:
                            Tclient=Tclient+str(char)
                        listeclient.append(str(Tclient).decode('utf-8'))
                presult=curs.execute("SELECT libel,idpres FROM prestations WHERE idadmin='"+str(poste["ADMINID"])+"' AND rang='0';")
                presult=curs.fetchall()
                presta['1','count']=0
                presta['2','count']=0
                presta['2','count']=0
                if presult:
                    u=1
                    for pchain in presult:
                        #print chain
                        p=0
                        T0presta=""
                        T0idpresta=""
                        for pchar in pchain:
                            if p==0:T0presta=T0presta+str(pchar)
                            if p==1:T0idpresta=T0idpresta+str(pchar)
                            p+=1
                        listeactivite.append(str(T0presta).decode('utf-8'))
                        presta[u,'0','0','label']=T0presta
                        presta[u,'0','0','id']=T0idpresta
                        presta['1','count']=u
                        ppresult=curs.execute("SELECT libel,idpres FROM prestations WHERE idadmin='"+str(poste["ADMINID"])+"' AND rang='1' AND mother='"+str(T0idpresta)+"';" )
                        ppresult=curs.fetchall()
                        if ppresult:
                            v=1
                            for ppchain in ppresult:
                                #print chain
                                pp=0
                                T1presta=""
                                T1idpresta=""
                                for ppchar in ppchain:
                                    if pp==0:T1presta=T1presta+str(ppchar)
                                    if pp==1:T1idpresta=T1idpresta+str(ppchar)
                                    pp+=1
                                listeactivite.append('  --  '+str(T1presta).decode('utf-8'))
                                presta[u,v,'0','label']='  --  '+str(T1presta).decode('utf-8')
                                presta[u,v,'0','id']=T1idpresta
                                presta['2','count']=v
                                pppresult=curs.execute("SELECT libel,idpres FROM prestations WHERE idadmin='"+str(poste["ADMINID"])+"' AND rang='2' AND mother='"+str(T1idpresta)+"';" )
                                pppresult=curs.fetchall()
                                if pppresult:
                                    w=1
                                    for pppchain in pppresult:
                                        #print chain
                                        ppp=0
                                        T2presta=""
                                        T2idpresta=""
                                        for pppchar in pppchain:
                                            if ppp==0:T2presta=T2presta+str(pppchar)
                                            if ppp==1:T2idpresta=T2idpresta+str(pppchar)
                                            ppp+=1
                                        listeactivite.append('  --  --  '+str(T2presta).decode('utf-8'))
                                        presta[u,v,w,'label']='  --  --  '+str(T2presta).decode('utf-8')
                                        presta[u,v,w,'id']=T2idpresta
                                        presta['3','count']=w
            
                                        w+=1            
                                v+=1
                        u+=1

                curs.close()
                conn.close()
            else:
                message="erreur : Faites le wizard avant"
        except:
            message="Connection internet requise"
        

    def ajouteFiltre(self,event):
        global Tcontenant,Tcontenu,Tpropriete,Tfiltre,Tclient,Tprestation,listeclient,listeactivite,listetache,message,filtre,fbox
        tpass=False
        if Tcontenant!="":
            tpass=True
        else:
            self.dc.message.SetLabel("Veuillez selectionner un contenant")
        if tpass==False:
            return
        tpass=False
        if Tpropriete!="":
            tpass=True
        else:
            self.dc.message.SetLabel("Veuillez selectionner une propriété")
        if tpass==False:
            return
        tpass=False
        if Tfiltre!="":
            tpass=True
        else:
            self.dc.message.SetLabel("Veuillez entrer un libellé au filtre")
        if tpass==False:
            return
        tpass=False
        if Tcontenu!="":
            tpass=True
        else:
            self.dc.message.SetLabel("Veuillez entrer la valeur contenue")
        if tpass==False:
            return
        tpass=False
        if Tclient!="":
            tpass=True
        else:
            self.dc.message.SetLabel("Veuillez selectionner une valeur pour client")
        if tpass==False:
            return
        tpass=False
        if Tprestation!="":
            tpass=True
        else:
            self.dc.message.SetLabel("Veuillez selectionner une valeur pour la prestation")
        if tpass==False:
            return   
        try:
            chemFS= oscurdir + os.sep + "wok"+os.sep+ "conf"+os.sep+"gaors.gwh"
            logfile = open(chemFS,'rb')
        except:
            chemFS= oscurdir + os.sep + "wok"+os.sep+ "need"+os.sep+"zero.gwh"
            logfile = open(chemFS,'rb')
            chemFS= oscurdir + os.sep + "wok"+os.sep+ "conf"+os.sep+"gaors.gwh"
        def Gdecrypt(outputin,result):
            xdecryptor=AES.new(str(ElChaloR[0:24]), AES.MODE_CBC,jak)
            chunksize=(64*1024)
            rep=''
            while True:
                chunk=''
                chunk=outputin.read(n=chunksize)
                if len(chunk)==0:
                    break
                elif len(chunk)%16!=0:
                    chunk += ' ' * (16-len(chunk) % 16 )
                rep=rep+xdecryptor.decrypt(chunk)
            logfile.close()
            result.write(rep)
            return result
                    
        outputin = StringIO.StringIO(logfile.read())
##                        outputin.write(logfile.read())
        result = StringIO.StringIO()
        #detr=obj.decrypt(outputin.getvalue())
        Gdecrypt(outputin,result)
        #result.write(detr)
        drunk=result.getvalue()
        lou=len(drunk)
        drink=''
        #print repr(drunk)
        for c in range(0,lou):
            try:
                if drunk[c:c+7]=='</PrsP>':
                    drink=drink+'</PrsP>'
                    break
                else:drink=drink+drunk[c]
            except:
                pass
        #print repr(drink)
        xim=xml.dom.minidom.parseString(drink)
        logfile.close()
        unem = xim.getElementsByTagName('FILTRE')
        for unam in unem:
            libelle=unam.getAttribute('Libelle')
            if libelle==Tfiltre:
                self.dc.message.SetLabel("libellé de filtre déjà utilisé")
                return
                            
        racine=xim.documentElement
        element =xim.createElement("FILTRE")
        element.setAttribute("Libelle",Tfiltre)
        element.setAttribute("Contenant",Tcontenant)
        element.setAttribute("Propriete",Tpropriete)
        element.setAttribute("Contenu",Tcontenu)
        element.setAttribute("Client",Tclient)
        element.setAttribute("Prestation",Tprestation)
        element.setAttribute("Prestationid",Tprestationid)
        racine.appendChild(element)
##        unem = xim.getElementsByTagName('FILTRE')
##        for x in range(1,int(filtre['nombre'])+1):
##            #print x
##            posy=(int(x)*10)
##            idx='235'+str(x)
##            self.dc.postboxp.Detach(fbox[x])
        #self.dc.postboxp.Clear(True)
        def Gencrypt(results,outputfile):
            encryptor=AES.new(str(ElChaloR[0:24]), AES.MODE_CBC,jak)
            #decryptor=AES.new(str(ElChaloR[0:24]), AES.MODE_CBC,jak)
            chunksize=(64*1024)
            mlogfile = open(outputfile, 'wb')
            ret=''
            while True:
                chunk = results.read(n=chunksize)
                if len(chunk)==0:
                    break
                elif len(chunk)%16!=0:
                    chunk += ' ' * (16-len(chunk) % 16 )                
                ret=ret+chunk
            djunky=encryptor.encrypt(ret)
            mlogfile.write(djunky)
            mlogfile.close()
        class TTransPak:
            def write(self,data):
                outputin.write(data.encode('utf-8'))
        outputin = StringIO.StringIO()
        xim.writexml(TTransPak(), encoding='utf-8')
        results = StringIO.StringIO(outputin.getvalue())        
        Gencrypt(results,chemFS)
        outputin.close()
        results.close()
        #self.ajouteFiltres()
        self.Destroy()
        Analyse(None, -1, 'Chronos Monitor',"Filtre ajouté")


    def ajouteFiltres(self):
        global filtre,fbox
        #self.dc.postboxp.Clear(True)
        for x in range(1,int(filtre['nombre'])+1):
            #print x
            posy=(int(x)*10)
            idx='580'+str(x)
            fbox[x]=wx.CheckBox(self.dc.panelp,int(idx),label=str(filtre['Libelle',int(x)]))
            self.dc.postboxp.Add(fbox[x],wx.LEFT)
            fbox[x].Bind(wx.EVT_CHECKBOX, self.OnFiltreCheck)
        #self.dc.postboxp.ShowItems(True)
    
    def retireFiltre(self,event):
        global filtre
        try:
            try:
                chemFS= oscurdir + os.sep + "wok"+os.sep+ "conf"+os.sep+"gaors.gwh"
                logfile = open(chemFS,'rb')
            except:
                chemFS= oscurdir + os.sep + "wok"+os.sep+ "need"+os.sep+"zero.gwh"
                logfile = open(chemFS,'rb')
                chemFS= oscurdir + os.sep + "wok"+os.sep+ "conf"+os.sep+"gaors.gwh"
            def Gdecrypt(outputin,result):
                xdecryptor=AES.new(str(ElChaloR[0:24]), AES.MODE_CBC,jak)
                chunksize=(64*1024)
                rep=''
                while True:
                    chunk=''
                    chunk=outputin.read(n=chunksize)
                    if len(chunk)==0:
                        break
                    elif len(chunk)%16!=0:
                        chunk += ' ' * (16-len(chunk) % 16 )
                    rep=rep+xdecryptor.decrypt(chunk)
                logfile.close()
                result.write(rep)
                return result
                        
            outputin = StringIO.StringIO(logfile.read())
    ##                        outputin.write(logfile.read())
            result = StringIO.StringIO()
            #detr=obj.decrypt(outputin.getvalue())
            Gdecrypt(outputin,result)
            #result.write(detr)
            drunk=result.getvalue()
            lou=len(drunk)
            drink=''
            #print repr(drunk)
            for c in range(0,lou):
                try:
                    if drunk[c:c+7]=='</PrsP>':
                        drink=drink+'</PrsP>'
                        break
                    else:drink=drink+drunk[c]
                except:
                    pass
            #print repr(drink)
            xim=xml.dom.minidom.parseString(drink)
            logfile.close()
            unem = xim.getElementsByTagName('FILTRE')
            racine=xim.documentElement
            for x in range(1,int(filtre['nombre'])+1):
                if filtre["checked",x]==True:
                    for unam in unem:
                        libelle=unam.getAttribute('Libelle')
                        if libelle==filtre['Libelle',x]:
                            racine.removeChild(unam)
                            print "removed"
            def Gencrypt(results,outputfile):
                encryptor=AES.new(str(ElChaloR[0:24]), AES.MODE_CBC,jak)
                #decryptor=AES.new(str(ElChaloR[0:24]), AES.MODE_CBC,jak)
                chunksize=(64*1024)
                mlogfile = open(outputfile, 'wb')
                ret=''
                while True:
                    chunk = results.read(n=chunksize)
                    if len(chunk)==0:
                        break
                    elif len(chunk)%16!=0:
                        chunk += ' ' * (16-len(chunk) % 16 )                
                    ret=ret+chunk
                djunky=encryptor.encrypt(ret)
                mlogfile.write(djunky)
                mlogfile.close()
            class TTransPak:
                def write(self,data):
                    outputin.write(data.encode('utf-8'))
            outputin = StringIO.StringIO()
            xim.writexml(TTransPak(), encoding='utf-8')
            results = StringIO.StringIO(outputin.getvalue())        
            Gencrypt(results,chemFS)
            outputin.close()
            results.close()
            self.Destroy()
            Analyse(None, -1, 'Chronos Monitor',"Filtres retirés")
        except:
            self.dc.message.SetLabel("erreur dans la gestion des filtres")
                            
    def messageLu(self,event):
        self.dc.message.SetLabel("")

##pnl1 = wx.Panel(self, -1, style=wx.SIMPLE_BORDER)
##pnl2 = wx.Panel(self, -1, style=wx.RAISED_BORDER)
##pnl3 = wx.Panel(self, -1, style=wx.SUNKEN_BORDER)
##pnl4 = wx.Panel(self, -1, style=wx.NO_BORDER) http://wiki.wxpython.org/AnotherTutorial#wx.GridBagSizer
  
    def Draw(self):
        global filtre,listeclient,listeactivite,fbox,message
        self.dc.SetFont(self.font)
        self.dc.font1 = wx.Font(8, wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_NORMAL, False)
       #wx.NullColour)
        #==================Panel Definition De Filtre=======================================
        self.dc.SetFont(self.dc.font1)
        self.dc.paneldefinition = wx.Panel ( self,-1,(10,30),(420,110), style=wx.SUNKEN_BORDER)
        self.dc.paneldefinition.SetBackgroundColour('#EAEAE9')
        self.dc.ajouter = wx.Button ( self.dc.paneldefinition, 100, 'Ajouter' ,pos=(335,80) )
        self.dc.ajouter.Bind(wx.EVT_BUTTON, self.ajouteFiltre )
        self.dc.lu = wx.Button ( self.dc.paneldefinition, 100, 'Message Lu' ,pos=(250,80))
        self.dc.lu.Bind(wx.EVT_BUTTON, self.messageLu )
        self.dc.si=wx.StaticText(self.dc.paneldefinition, -1, label="Si :",pos=(3,8))
        self.dc.si.SetBackgroundColour('#EAEAE9')
        self.dc.alors=wx.StaticText(self.dc.paneldefinition, -1, label="Alors :",pos=(3,32))
        self.dc.alors.SetBackgroundColour('#EAEAE9')
        self.dc.message = wx.StaticText(self.dc.paneldefinition, -1, message,pos=(3,85))
        self.dc.message.SetBackgroundColour('#EAEAE9')
        self.dc.libelleclient=wx.StaticText(self.dc.paneldefinition, -1, label="Client = ",pos=(36,32))
        self.dc.libelleclient.SetBackgroundColour('#EAEAE9')
        self.dc.libelleactivite=wx.StaticText(self.dc.paneldefinition, -1, label="Prestation = ",pos=(3,57))
        self.dc.libelleactivite.SetBackgroundColour('#EAEAE9')
        #self.dc.libelletache = wx.StaticText(self.dc.paneldefinition, -1, 'Tache =',pos=(3,85))
        #self.dc.libelletache.SetBackgroundColour('#EAEAE9')
        self.dc.libellefiltre = wx.StaticText(self.dc.paneldefinition, -1, 'Libellé du filtre :',pos=(250,32))
        self.dc.libellefiltre.SetBackgroundColour('#EAEAE9')
        contenants = ['Le libellé de la fenêtre', 'Le chemin du processus', 'Le nom du processus', 'Le chemin du fichier', 'Le nom du fichier']
        self.dc.contenants = wx.ComboBox(self.dc.paneldefinition, 2856, size=(125, -1),pos=(22,5), choices=contenants, style=wx.CB_READONLY)
        self.dc.contenants.Bind(wx.EVT_COMBOBOX, self.OnContSelect)
        propriete = ['contient', 'est égal à']
        self.dc.propriete = wx.ComboBox(self.dc.paneldefinition, 2857, size=(73, -1),pos=(152,5), choices=propriete, style=wx.CB_READONLY)
        self.dc.propriete.Bind(wx.EVT_COMBOBOX, self.OnPropSelect)
        self.dc.contenu=wx.TextCtrl(self.dc.paneldefinition, 2858, size=(185, -1),pos=(230,5))
        self.dc.contenu.Bind(wx.EVT_TEXT, self.OnContenuSelect)
        self.dc.nomfiltre=wx.TextCtrl(self.dc.paneldefinition, 2859, size=(85, -1),pos=(330,30))
        self.dc.nomfiltre.Bind(wx.EVT_TEXT, self.OnFiltreSelect)

        self.dc.client = wx.ComboBox(self.dc.paneldefinition, 2860, size=(165,-1),pos=(77,30), choices=listeclient, style=wx.CB_READONLY | wx.EXPAND )
        self.dc.client.Bind(wx.EVT_COMBOBOX, self.OnClientSelect)
        self.dc.activite = wx.ComboBox(self.dc.paneldefinition, 2861, size=(345, -1),pos=(70,55), choices=listeactivite, style=wx.CB_READONLY)
        self.dc.activite.Bind(wx.EVT_COMBOBOX, self.OnPrestaSelect)



        #==================Panel Liste de Filtres===========================================,pos=(10,30)
        self.dc.panelp=scrolled.ScrolledPanel(self,-1,(10,150),(150,120), style=wx.SUNKEN_BORDER)
        self.dc.panelp.SetupScrolling(scroll_x=True,scroll_y=True)
        self.dc.panelp.SetBackgroundColour('#EAEAE9')
        self.dc.DrawBitmap(self.fond, 10, 300, True)
        self.dc.postboxp=wx.BoxSizer(wx.VERTICAL)
        fbox={}
        for x in range(1,int(filtre['nombre'])+1):
            #print x
            posy=(int(x)*10)
            idx='580'+str(x)
            fbox[x]=wx.CheckBox(self.dc.panelp,int(idx),label=str(filtre['Libelle',int(x)]))
            self.dc.postboxp.Add(fbox[x],wx.LEFT)
            fbox[x].Bind(wx.EVT_CHECKBOX, self.OnFiltreCheck)
        self.dc.export = wx.Button ( self, 100, 'Retirer',pos=(170,248) )
        self.dc.export.Bind(wx.EVT_BUTTON, self.retireFiltre )
        self.dc.panelp.SetSizer(self.dc.postboxp)
        self.dc.postboxp.FitInside(self.dc.panelp)
        #=================Panel Affichage du Filtre==========================================
        self.dc.panel = wx.Panel ( self,-1,(170,150),(260,90), style=wx.SUNKEN_BORDER)
        self.dc.panel.SetBackgroundColour('#EAEAE9')
        self.dc.contenanttxt = wx.StaticText(self.dc.panel, -1, "",pos=(5,5))
        self.dc.contenanttxt.SetBackgroundColour('#EAEAE9')
        self.dc.contenutxt = wx.StaticText(self.dc.panel, -1, "",pos=(5,25))
        self.dc.contenutxt.SetBackgroundColour('#EAEAE9')
        self.dc.clienttxt = wx.StaticText(self.dc.panel, -1, "",pos=(5,45))
        self.dc.clienttxt.SetBackgroundColour('#EAEAE9')
        self.dc.activitetxt = wx.StaticText(self.dc.panel, -1, "",pos=(5,65))
        self.dc.activitetxt.SetBackgroundColour('#EAEAE9')



        self.Show ( True )
        
    def OnPaint(self, event):
        wx.BufferedPaintDC(self,self.bitmap)
        self.chargeFiltres()
        self.chargeDonnees()
        self.Draw()
        event.Skip()



        
    def OnLeftDown(self, event):
        global message,vtp,line1,line2,line3,reset
        #self.bdc = wx.BufferedDC(self.cdc)
        pos = event.GetPosition()
##        self.dc.nkey.SelectAll()
##        self.key = self.dc.nkey.GetValue()
##        self.dc.nkey.Clear()
#        print "+"+repr(self.key)+"+"
        if self.closeRegion.ContainsPoint(pos):
            self.Close()
        elif self.validRegion.ContainsPoint(pos):
            wx.BufferedDC(wx.ClientDC(self),self.valida)
            self.Close()
                
        x, y = self.ClientToScreen(event.GetPosition())
        ox, oy = self.GetPosition()
        dx = x - ox
        dy = y - oy
        self.delta = ((dx, dy))


    def OnMouseMove(self, event):
        global enter,line1,line2,line3
        pos = event.GetPosition()
        if self.closeRegion.ContainsPoint(pos):
            wx.BufferedDC(wx.ClientDC(self),self.closer)
            enter=True
        elif self.validRegion.ContainsPoint(pos):
            wx.BufferedDC(wx.ClientDC(self),self.validr)
            enter=True
        else:
            if enter==True:
                wx.BufferedDC(wx.ClientDC(self),self.bitmap)
                enter=False          

        if event.Dragging() and event.LeftIsDown():
            x, y = self.ClientToScreen(event.GetPosition())
            fp = (x - self.delta[0], y - self.delta[1])
            self.Move(fp)
        #print enter
        event.Skip()



class Export(wx.Frame):
    global reset,jak,dina,message,vtp,line1,line2,line3,ElChaloR,oscurdir,encfile,checkfichier
    def __init__(self, parent, id, title):
        global reset,jak,dina,message,vtp,line1,line2,line3,ElChaloR,oscurdir,encfile,checkfichier
        wx.Frame.__init__(self, parent, id, title, size=(250, 150),style=wx.FRAME_SHAPED |wx.FRAME_NO_TASKBAR|wx.NO_BORDER)

        self.font = wx.Font(11, wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL, 
		wx.FONTWEIGHT_BOLD, False, 'Comic Sans MS')

        #self.panel=wx.Panel(self,-1)

        self.hasShape=False
        self.delta=(0,0)

        self.image_file = 'img/export.gif'
        self.bmp = wx.Bitmap(self.image_file, wx.BITMAP_TYPE_GIF)
        #bg=wx.StaticBitmap(self.panel, wx.ID_ANY, bmp, (0, 0))
        
        self.bitmap = wx.Bitmap('img/export-normal.png', wx.BITMAP_TYPE_PNG)
        self.closer = wx.Bitmap('img/export-close.png', wx.BITMAP_TYPE_PNG)
        self.close = wx.Bitmap('img/close-normal.png', wx.BITMAP_TYPE_PNG)
        self.valida = wx.Bitmap('img/dossier-appui.png', wx.BITMAP_TYPE_PNG)
        self.validr = wx.Bitmap('img/export-rollover.png', wx.BITMAP_TYPE_PNG)
        self.valid = wx.Bitmap('img/valider-normal.png', wx.BITMAP_TYPE_PNG)
        self.fond = wx.Bitmap('img/wizard-fond.png', wx.BITMAP_TYPE_PNG)

        def get_main_dir():
            try:
                sys.frozen
            except AttributeError:
                path = sys.argv[0]
            else:
                path = sys.executable
            return os.path.dirname(os.path.abspath(path))

        oscurdir=get_main_dir()
        encfile={}
        checkfichier={}
        jak='2164691737824342'
        

        self.SetClientSize((self.bitmap.GetWidth(), self.bitmap.GetHeight()))

        if wx.Platform == '__WXGTK__':
            self.Bind(wx.EVT_WINDOW_CREATE, self.SetNoteShape)
        else: self.SetNoteShape()

        line1="Rendez Vous sur :"
        line2="http://www.chronosmonitor.fr"
        line3="Pour obtenir une clef d'activation"  
        enter=False         
        self.SetTransparent(int(deltatrsp))
        self.Bind(wx.EVT_PAINT, self.OnPaint)
        self.Bind(wx.EVT_LEFT_DOWN, self.OnLeftDown)
        self.Bind(wx.EVT_LEFT_DOWN, self.OnLeftDown)
        self.Bind(wx.EVT_MOTION, self.OnMouseMove)

        self.bitmapRegion = wx.RegionFromBitmap(self.bitmap)
        self.validRegion = wx.RegionFromBitmap(self.valid)
        self.closeRegion = wx.RegionFromBitmap(self.close)


        self.validRegion.IntersectRegion(self.bitmapRegion)
        self.validRegion.Offset(316, 242)

        self.closeRegion.IntersectRegion(self.bitmapRegion)
        self.closeRegion.Offset(408, 12)
      

        self.dc = wx.ClientDC(self)
        self.dc.DrawBitmap(self.bitmap, 0, 0, True)
        self.Show(True)
        self.Fit()
        self.Centre()



    def SetNoteShape(self, *event):
        #region=wx.RegionFromBitmapColour(self.bitmap,'#000000',0)
        region = wx.RegionFromBitmap(self.bmp)
        self.hasShape=self.SetShape(region)


    def OnClicked(self, event):
        #print 'event reached frame class'
        event.Skip()


    def OnKey(self,event):

        pass

    def OnRadio(self,event):
        pass
        





    def OnApply(self,event):
        pass
    
    def Export(self,event):
        pass

    def OnTTexT(self,event):
        global dtp
        dtp=event.GetString()

    def OnDTexT(self,event):
        global dina
        dina=event.GetString()



    def OnFichierCheck(self,event):
        global checkfichier
        uzer=event.GetId()
##        p=0
        hip=int(uzer)
##        for char in str(uzer):
##            if p >3:
##                hip=str(hip)+str(char)
##            p+=1
##        print hip
        user = wx.FindWindowById(int(uzer))
        if user.GetValue():
            checkfichier["Checked",int(hip)]=True
        else:
            checkfichier["Checked",int(hip)]=False

    def DShow(self):
        self.dc.DrawText("Choisissez les fichiers à exporter :",10,30)

    def chargeFichiers(self):
        global encfile
        x=1
        encdir=os.curdir+os.sep+'wok'+os.sep+'enc'
        for f in os.listdir(encdir):
            if os.path.isdir(os.path.join(encdir, f)):
                chemr=os.path.join(encdir, f)
                for fic in os.listdir(chemr):
                    if os.path.isfile(os.path.join(chemr, fic)):
                        chem=os.path.join(chemr, fic)
                        flo=len(chem)
                        fichier=""
                        for fm in range(0,flo-4):
                            if chem[fm]==os.sep:
                                fichier=""
                            else:
                                fichier=fichier+chem[fm]

                        encfile['path',x]=fichier
                        encfile['nombre']=x
                        checkfichier["Checked",x]=False
                        x+=1

    def Export(self,event):
        global obj,encfile,checkfichier
        try:
            message="erreur lors de l'exportation"
            encdir=os.curdir+os.sep+'wok'+os.sep+'enc'
            for f in os.listdir(encdir):
                if os.path.isdir(os.path.join(encdir, f)):
                    chemr=os.path.join(encdir, f)
                    for fic in os.listdir(chemr):
                        if os.path.isfile(os.path.join(chemr, fic)):
                            chem=os.path.join(chemr, fic)
                            flo=len(chem)
                            fichier=""
                            for fm in range(0,flo-4):
                                if chem[fm]==os.sep:
                                    fichier=""
                                else:
                                    fichier=fichier+chem[fm]
                            nochecked=False
                            for x in range(1,int(encfile['nombre'])+1):
                                if encfile['path',x]==fichier:
                                    if checkfichier["Checked",x]==False:
                                        nochecked=True
                            if nochecked==True:
                                continue
                            tze=1
                            rrept=chem
                            xil=len(chem)

                            tze=0
                            rrept=chem
                            logfile = open(rrept, mode ='rb')
                            def Gdecrypt(outputin,result):
                                xdecryptor=AES.new(str(ElChaloR[0:24]), AES.MODE_CBC,jak)
                                chunksize=(64*1024)
                                rep=''
                                while True:
                                    chunk=''
                                    chunk=outputin.read(n=chunksize)
                                    if len(chunk)==0:
                                        break
                                    elif len(chunk)%16!=0:
                                        chunk += ' ' * (16-len(chunk) % 16 )
                                    rep=rep+xdecryptor.decrypt(chunk)
                                logfile.close()
                                result.write(rep)
                                return result
                                        
                            outputin = StringIO.StringIO(logfile.read())
    ##                        outputin.write(logfile.read())
                            result = StringIO.StringIO()
                            #detr=obj.decrypt(outputin.getvalue())
                            Gdecrypt(outputin,result)
                            #result.write(detr)
                            drunk=result.getvalue()
                            lou=len(drunk)
                            drink=''
                            #print repr(drunk)
                            for c in range(0,lou):
                                try:
                                    if drunk[c:c+7]=='</PrsP>':
                                        drink=drink+'</PrsP>'
                                        break
                                    else:drink=drink+drunk[c]
                                except:
                                    pass
                            #print repr(drink)
                            XTCstring=xml.dom.minidom.parseString(drink)
                            outputin.close()
                            result.close()
                            x=0
                            ligne={}
                            lino={}
                            kp=len(fic)
                            chemt=os.curdir+os.sep+'export'+os.sep+fic[0:kp-4]+'.csv'
                            
                            logfile = open(chemt, mode ='w')
                            def MTWrite(data):
                                logfile.write(data.encode('utf-16'))
                            lines = XTCstring.getElementsByTagName('PrsP')
                            for line in lines:
                                ligne[x]=line.getAttribute('ReportLine')#.decode('iso-8859-1')
                                lino[x]=""
                                line=ligne[x]
                                ln=len(line)
                                
                                for w in range(0,ln):
                                    char=line[w:w+1]
                                    icar=line[w:w+2]
                                    if char=="#":
                                        lino[x]=lino[x]+'\t'
                                    else:
                                        lino[x]=lino[x]+char
                                x+=1

                            for c in range(0,x):
                                MTWrite(lino[c]+'\n')
                            logfile.close()
        finally:
            message="Les fichiers ont été exportés dans le dossier export"
        self.dc.message.SetLabel(message)


 
    def Lu(self,event):
        self.dc.message.SetLabel('')




    
    def Draw(self):
        global encfile
        self.dc.SetFont(self.font)
        self.dc.font1 = wx.Font(8, wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_NORMAL, False)
       #wx.NullColour)
        #self.dc.SetTextForeground()
        self.dc.SetFont(self.dc.font1)
        self.dc.SetTextBackground(wx.NullColour)
        self.dc.SetTextForeground('#6C8D91')
        self.dc.DrawText("Choisissez les fichiers à exporter :",10,30)
        self.dc.panelp=scrolled.ScrolledPanel(self,-1,(10,50),(200,120), style=wx.SUNKEN_BORDER)
        self.dc.panelp.SetupScrolling(scroll_x=True,scroll_y=True)
        self.dc.panelp.SetBackgroundColour('#EAEAE9')
        self.dc.DrawBitmap(self.fond, 10, 300, True)
        #self.dc.panel=MyScrollPanel(self.dc)
        self.dc.postboxp=wx.BoxSizer(wx.VERTICAL)
        self.dc.box={}
        for x in range(1,int(encfile['nombre'])+1):
            #print x
            posy=(int(x)*10)
            idx=int(x)
            self.dc.box[x]=wx.CheckBox(self.dc.panelp,int(idx),label=str(encfile['path',int(x)]))
            self.dc.postboxp.Add(self.dc.box[x],wx.LEFT)
            self.dc.box[x].Bind(wx.EVT_CHECKBOX, self.OnFichierCheck)
        self.dc.panelp.SetSizer(self.dc.postboxp)
        self.dc.postboxp.FitInside(self.dc.panelp)
        self.dc.panel = wx.Panel ( self,-1,(10,170),(400,70), style=wx.SUNKEN_BORDER)
        self.dc.panel.SetBackgroundColour('#EAEAE9')
        self.dc.message = wx.StaticText(self.dc.panel, -1, '',pos=(10,10))
        self.dc.export = wx.Button ( self.dc.panel, 100, 'Export',pos=(10,30) )
        self.dc.export.Bind(wx.EVT_BUTTON, self.Export )
        self.dc.lu = wx.Button ( self.dc.panel, 100, 'Lu',pos=(100,30) )
        self.dc.lu.Bind(wx.EVT_BUTTON, self.Lu )
        self.Show ( True )
        
    def OnPaint(self, event):
        global postes,users,dc,box,panelp

        wx.BufferedPaintDC(self,self.bitmap)
        self.chargeFichiers()
        self.Draw()
        event.Skip()



        
    def OnLeftDown(self, event):
        global message,vtp,line1,line2,line3,reset
        #self.bdc = wx.BufferedDC(self.cdc)
        pos = event.GetPosition()
##        self.dc.nkey.SelectAll()
##        self.key = self.dc.nkey.GetValue()
##        self.dc.nkey.Clear()
#        print "+"+repr(self.key)+"+"
        if self.closeRegion.ContainsPoint(pos):
            self.Close()
        elif self.validRegion.ContainsPoint(pos):
            wx.BufferedDC(wx.ClientDC(self),self.valida)
##            self.verifyTransparency()
##            self.verifyDina()
##            try:
##                self.saveConfig()
##                try:
##                    if str(vtp)=="OK":
##                        reset=True
##                        line1="Configuration enregistrée."
##                        line2="Le widget la prendra en compte"
##                        line3="d'içi 10 secondes."
##                        self.Close()
##                        WizardEnd(None, 465, 'Chronos Monitor Configuration')
##                    elif str(vtp)=="NOT":
##                        self.dc.message.SetLabel(message)
##                except:
##                    self.dc.message.SetLabel(message)
##            except:
##                self.dc.message.SetLabel(message)
            self.Close()
        x, y = self.ClientToScreen(event.GetPosition())
        ox, oy = self.GetPosition()
        dx = x - ox
        dy = y - oy
        self.delta = ((dx, dy))


    def OnMouseMove(self, event):
        global enter,line1,line2,line3
        pos = event.GetPosition()
        if self.closeRegion.ContainsPoint(pos):
            wx.BufferedDC(wx.ClientDC(self),self.closer)
            self.DShow()
            enter=True
        elif self.validRegion.ContainsPoint(pos):
            wx.BufferedDC(wx.ClientDC(self),self.validr)
            self.DShow()
            enter=True
        else:
            if enter==True:
                wx.BufferedDC(wx.ClientDC(self),self.bitmap)
                self.DShow()
                enter=False          

        if event.Dragging() and event.LeftIsDown():
            x, y = self.ClientToScreen(event.GetPosition())
            fp = (x - self.delta[0], y - self.delta[1])
            self.Move(fp)
        #print enter
        event.Skip()

class Dossiers(wx.Frame):
    global reset,jak,dina,message,vtp,line1,line2,line3,ElChaloR,oscurdir,dossier,undossier,explorer,logfull
    def __init__(self, parent, id, title):
        global reset,jak,dina,message,vtp,line1,line2,line3,ElChaloR,oscurdir,dossier,undossier,explorer,path,logfull
        wx.Frame.__init__(self, parent, id, title, size=(250, 150),style=wx.FRAME_SHAPED |wx.FRAME_NO_TASKBAR|wx.NO_BORDER)

        self.font = wx.Font(11, wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL, 
		wx.FONTWEIGHT_BOLD, False, 'Comic Sans MS')

        #self.panel=wx.Panel(self,-1)

        self.hasShape=False
        self.delta=(0,0)

        self.image_file = 'img/parametres_0.gif'
        self.bmp = wx.Bitmap(self.image_file, wx.BITMAP_TYPE_GIF)
        #bg=wx.StaticBitmap(self.panel, wx.ID_ANY, bmp, (0, 0))
        
        self.bitmap = wx.Bitmap('img/dossier-normal.png', wx.BITMAP_TYPE_PNG)
        self.closer = wx.Bitmap('img/dossier-close.png', wx.BITMAP_TYPE_PNG)
        self.close = wx.Bitmap('img/close-normal.png', wx.BITMAP_TYPE_PNG)
        self.valida = wx.Bitmap('img/dossier-appui.png', wx.BITMAP_TYPE_PNG)
        self.validr = wx.Bitmap('img/dossier-rollover.png', wx.BITMAP_TYPE_PNG)
        self.valid = wx.Bitmap('img/valider-normal.png', wx.BITMAP_TYPE_PNG)
        self.fond = wx.Bitmap('img/wizard-fond.png', wx.BITMAP_TYPE_PNG)

        def get_main_dir():
            try:
                sys.frozen
            except AttributeError:
                path = sys.argv[0]
            else:
                path = sys.executable
            return os.path.dirname(os.path.abspath(path))

        oscurdir=get_main_dir()
        dossier={}
        undossier={}
        jak='2164691737824342'
        

        self.SetClientSize((self.bitmap.GetWidth(), self.bitmap.GetHeight()))

        if wx.Platform == '__WXGTK__':
            self.Bind(wx.EVT_WINDOW_CREATE, self.SetNoteShape)
        else: self.SetNoteShape()

        line1="Rendez Vous sur :"
        line2="http://www.chronosmonitor.fr"
        line3="Pour obtenir une clef d'activation"  
        enter=False
        path=""
        self.SetTransparent(int(deltatrsp))
        self.Bind(wx.EVT_PAINT, self.OnPaint)
        self.Bind(wx.EVT_LEFT_DOWN, self.OnLeftDown)
        self.Bind(wx.EVT_LEFT_DOWN, self.OnLeftDown)
        self.Bind(wx.EVT_MOTION, self.OnMouseMove)

        self.bitmapRegion = wx.RegionFromBitmap(self.bitmap)
        self.validRegion = wx.RegionFromBitmap(self.valid)
        self.closeRegion = wx.RegionFromBitmap(self.close)


        self.validRegion.IntersectRegion(self.bitmapRegion)
        self.validRegion.Offset(316, 242)

        self.closeRegion.IntersectRegion(self.bitmapRegion)
        self.closeRegion.Offset(408, 12)
      

        self.dc = wx.ClientDC(self)
        self.dc.DrawBitmap(self.bitmap, 0, 0, True)
        self.Show(True)
        self.Fit()
        self.Centre()
        message='Choisissez les dossier a superviser'



    def SetNoteShape(self, *event):
        #region=wx.RegionFromBitmapColour(self.bitmap,'#000000',0)
        region = wx.RegionFromBitmap(self.bmp)
        self.hasShape=self.SetShape(region)


    def OnClicked(self, event):
        #print 'event reached frame class'
        event.Skip()


    def OnKey(self,event):

        pass

    def OnRadio(self,event):
        pass
        





    def OnApply(self,event):
        pass
    
    def Export(self,event):
        pass

    def OnPathSelect(self,event):
        global path
        path=event.GetString()

    def OnDTexT(self,event):
        global dina
        dina=event.GetString()



    def OnDossierCheck(self,event):
        global undossier
        uzer=event.GetId()
        p=0
        hip=""
        for char in str(uzer):
            if p >2:
                hip=hip+char
            p+=1
        user = wx.FindWindowById(int(uzer))
        if user.GetValue():
            undossier["Checked",int(hip)]=True
        else:
            undossier["Checked",int(hip)]=False


    def OnExplorerCheck(self,event):
        global explorer
        uzer=event.GetId()
        user = wx.FindWindowById(int(uzer))
        if user.GetValue():
            explorer=True
        else:
            explorer=False

    def OnLogFullCheck(self,event):
        global logfull
        uzer=event.GetId()
        user = wx.FindWindowById(int(uzer))
        if user.GetValue():
            logfull=True
        else:
            logfull=False
            
    def chargeDossier(self):
        global dossier,path,logfull
        try:
            chemFS= oscurdir + os.sep + "wok"+os.sep+ "conf"+os.sep+"resap.gwh"
            logfile = open(chemFS,'rb')
        except:
            chemFS= oscurdir + os.sep + "wok"+os.sep+ "need"+os.sep+"zero.gwh"
            logfile = open(chemFS,'rb')
        def Gdecrypt(outputin,result):
            xdecryptor=AES.new(str(ElChaloR[0:24]), AES.MODE_CBC,jak)
            chunksize=(64*1024)
            rep=''
            while True:
                chunk=''
                chunk=outputin.read(n=chunksize)
                if len(chunk)==0:
                    break
                elif len(chunk)%16!=0:
                    chunk += ' ' * (16-len(chunk) % 16 )
                rep=rep+xdecryptor.decrypt(chunk)
            logfile.close()
            result.write(rep)
            return result
                    
        outputin = StringIO.StringIO(logfile.read())
##                        outputin.write(logfile.read())
        result = StringIO.StringIO()
        #detr=obj.decrypt(outputin.getvalue())
        Gdecrypt(outputin,result)
        #result.write(detr)
        drunk=result.getvalue()
        lou=len(drunk)
        drink=''
        #print repr(drunk)
        for c in range(0,lou):
            try:
                if drunk[c:c+7]=='</PrsP>':
                    drink=drink+'</PrsP>'
                    break
                else:drink=drink+drunk[c]
            except:
                pass
        #print repr(drink)
        xim=xml.dom.minidom.parseString(drink)
        logfile.close()
        racine=xim.documentElement
        unem = xim.getElementsByTagName('DIR')
        x=1
        dossier['nombre']=0
        for unam in unem:
            dossier['path',x]=unam.getAttribute('PATH')
            dossier['nombre']=x
            x+=1
        lunem = xim.getElementsByTagName('EXPLORER')
        explorer=False
        for lunam in lunem:
            explorer=lunam.getAttribute('VALUE')
        if explorer=='False':
            explorer=False
        if explorer=='True':
            explorer=True
        punem = xim.getElementsByTagName('BACKPATH')
        for punam in punem:
            path=punam.getAttribute('PATH')
        logfull=False
        upunem = xim.getElementsByTagName('LOGFULL')
        for upunam in upunem:
            logfull=upunam.getAttribute('VALUE')
    
        if logfull=='False':
            logfull=False
        if logfull=='True':
            logfull=True    
    def newDir(self,event):
        global i,root,UserButton,dvariable,explorer,logfull
        desktop_pidl = shell.SHGetFolderLocation (0, shellcon.CSIDL_DESKTOP, 0, 0)
        pidl, display_name, image_list = shell.SHBrowseForFolder (
          win32gui.GetDesktopWindow (),
          desktop_pidl,
          "Choissez un repertoire",
          0,
          None,
          None
        )
        if shell.SHGetPathFromIDList (pidl)=="":
          mes.set("aucun repertoire selectionne")
          return
        else:path=shell.SHGetPathFromIDList (pidl)
##        try:
        try:
            chemFS= oscurdir + os.sep + "wok"+os.sep+ "conf"+os.sep+"resap.gwh"
            logfile = open(chemFS,'rb')
            zero=False
        except:
            chemFS= oscurdir + os.sep + "wok"+os.sep+ "need"+os.sep+"zero.gwh"
            logfile = open(chemFS,'rb')
            chemFS= oscurdir + os.sep + "wok"+os.sep+ "conf"+os.sep+"resap.gwh"
            zero=True
        def Gdecrypt(outputin,result):
            xdecryptor=AES.new(str(ElChaloR[0:24]), AES.MODE_CBC,jak)
            chunksize=(64*1024)
            rep=''
            while True:
                chunk=''
                chunk=outputin.read(n=chunksize)
                if len(chunk)==0:
                    break
                elif len(chunk)%16!=0:
                    chunk += ' ' * (16-len(chunk) % 16 )
                rep=rep+xdecryptor.decrypt(chunk)
            logfile.close()
            result.write(rep)
            return result
        def Gencrypt(results,outputfile):
            encryptor=AES.new(str(ElChaloR[0:24]), AES.MODE_CBC,jak)
            #decryptor=AES.new(str(ElChaloR[0:24]), AES.MODE_CBC,jak)
            chunksize=(64*1024)
            mlogfile = open(outputfile, 'wb')
            ret=''
            while True:
                chunk = results.read(n=chunksize)
                if len(chunk)==0:
                    break
                elif len(chunk)%16!=0:
                    chunk += ' ' * (16-len(chunk) % 16 )                
                ret=ret+chunk
            djunky=encryptor.encrypt(ret)
            mlogfile.write(djunky)
            mlogfile.close()
        class TTransPak:
            def write(self,data):
                outputin.write(data.encode('utf-8'))                    
        outputin = StringIO.StringIO(logfile.read())
##                        outputin.write(logfile.read())
        result = StringIO.StringIO()
        #detr=obj.decrypt(outputin.getvalue())
        Gdecrypt(outputin,result)
        outputin.close()
        #result.write(detr)
        drunk=result.getvalue()
        result.close()
        lou=len(drunk)
        drink=''
        #print repr(drunk)
        for c in range(0,lou):
            try:
                if drunk[c:c+7]=='</PrsP>':
                    drink=drink+'</PrsP>'
                    break
                else:drink=drink+drunk[c]
            except:
                pass
        #print repr(drink)
        xim=xml.dom.minidom.parseString(drink)
        logfile.close()

        racine=xim.documentElement
        element =xim.createElement("DIR")
        element.setAttribute("PATH",str(path))
        racine.appendChild(element)
 
        if zero==True:

            element =xim.createElement("EXPLORER")
            element.setAttribute("VALUE",str(explorer))
            racine.appendChild(element)
            element =xim.createElement("BACKPATH")
            element.setAttribute("PATH",str(path))
            element =xim.createElement("LOGFULL")
            element.setAttribute("VALUE",str(logfull))
            racine.appendChild(element)

            outputin = StringIO.StringIO()
            xim.writexml(TTransPak(), encoding='utf-8')
            results = StringIO.StringIO(outputin.getvalue())

            Gencrypt(results,chemFS)
            outputin.close()
            results.close()

    ##        self.dunlog()
    ##        self.chargeDossier()
    ##        self.dreinit()
            self.Destroy()
            Dossiers(None, -1, 'Chronos Monitor')
  

        elif zero==False:
            try:
                xorb=False
                unem = xim.getElementsByTagName('EXPLORER')
                for unam in unem:
                    unam.setAttribute("VALUE",str(explorer))
                    xorb=True

                if xorb==False:
                    element =xim.createElement("EXPLORER")
                    element.setAttribute("VALUE",str(explorer))
                    racine.appendChild(element)                    
                    
            except:
                element =xim.createElement("EXPLORER")
                element.setAttribute("VALUE",str(explorer))
                racine.appendChild(element)

            try:
                nunem = xim.getElementsByTagName('BACKPATH')
                xorb=False
                for nunam in nunem:
                    nunam.setAttribute("PATH",str(path))
                    xorb=True
                if xorb==False:
                    element =xim.createElement("BACKPATH")
                    element.setAttribute("PATH",str(path))
                    racine.appendChild(element)                  
            except:
                element =xim.createElement("BACKPATH")
                element.setAttribute("PATH",str(path))
                racine.appendChild(element)
            try:

                xorb=False
                pnunem = xim.getElementsByTagName('LOGFULL')                
                for pnunam in pnunem:
                    pnunam.setAttribute("VALUE",str(logfull))

                    xorb=True
                if xorb==False:

                    element =xim.createElement("LOGFULL")
                    element.setAttribute("VALUE",str(logfull))
                    racine.appendChild(element)

            except:

                element =xim.createElement("LOGFULL")
                element.setAttribute("VALUE",str(logfull))
                racine.appendChild(element)
            message="changements sauvegardés"

            outputin = StringIO.StringIO()
            xim.writexml(TTransPak(), encoding='utf-8')
            results = StringIO.StringIO(outputin.getvalue())

            Gencrypt(results,chemFS)
            outputin.close()
            results.close()

    ##        self.dunlog()
    ##        self.chargeDossier()
    ##        self.dreinit()
            self.Destroy()
            Dossiers(None, -1, 'Chronos Monitor')

##        except:
##            print 'erreur newdir'


    def dirDelete(self,event):
        global undossier
        #try:
        try:
            chemFS= oscurdir + os.sep + "wok"+os.sep+ "conf"+os.sep+"resap.gwh"
            logfile = open(chemFS,'rb')
        except:
            chemFS= oscurdir + os.sep + "wok"+os.sep+ "need"+os.sep+"zero.gwh"
            logfile = open(chemFS,'rb')
            chemFS= oscurdir + os.sep + "wok"+os.sep+ "conf"+os.sep+"resap.gwh"
        def Gdecrypt(outputin,result):
            xdecryptor=AES.new(str(ElChaloR[0:24]), AES.MODE_CBC,jak)
            chunksize=(64*1024)
            rep=''
            while True:
                chunk=''
                chunk=outputin.read(n=chunksize)
                if len(chunk)==0:
                    break
                elif len(chunk)%16!=0:
                    chunk += ' ' * (16-len(chunk) % 16 )
                rep=rep+xdecryptor.decrypt(chunk)
            logfile.close()
            result.write(rep)
            return result
                    
        outputin = StringIO.StringIO(logfile.read())
##                        outputin.write(logfile.read())
        result = StringIO.StringIO()
        #detr=obj.decrypt(outputin.getvalue())
        Gdecrypt(outputin,result)
        #result.write(detr)
        drunk=result.getvalue()
        lou=len(drunk)
        drink=''
        #print repr(drunk)
        for c in range(0,lou):
            try:
                if drunk[c:c+7]=='</PrsP>':
                    drink=drink+'</PrsP>'
                    break
                else:drink=drink+drunk[c]
            except:
                pass
        #print repr(drink)
        xim=xml.dom.minidom.parseString(drink)
        logfile.close()
        racine=xim.documentElement
        unem = xim.getElementsByTagName('DIR')
        x=1
        for unam in unem:
            hlog=unam.getAttribute('PATH')
            try:
                if undossier["Checked",int(x)]==True:
                    racine.removeChild(unam)
            except:
                pass
            x+=1

        def Gencrypt(results,outputfile):
            encryptor=AES.new(str(ElChaloR[0:24]), AES.MODE_CBC,jak)
            #decryptor=AES.new(str(ElChaloR[0:24]), AES.MODE_CBC,jak)
            chunksize=(64*1024)
            mlogfile = open(outputfile, 'wb')
            ret=''
            while True:
                chunk = results.read(n=chunksize)
                if len(chunk)==0:
                    break
                elif len(chunk)%16!=0:
                    chunk += ' ' * (16-len(chunk) % 16 )                
                ret=ret+chunk
            djunky=encryptor.encrypt(ret)
            mlogfile.write(djunky)
            mlogfile.close()
        class TTransPak:
            def write(self,data):
                outputin.write(data.encode('utf-8'))
        outputin = StringIO.StringIO()
        xim.writexml(TTransPak(), encoding='utf-8')
        results = StringIO.StringIO(outputin.getvalue())        
        Gencrypt(results,chemFS)
        outputin.close()
        results.close()

        self.Destroy()
        Dossiers(None, -1, 'Chronos Monitor')

    def dunlog(self):
        global dossier
        #try:
        for x in range(0,int(dossier['nombre'])):
            print 'dunlog',x
            idx='480'+str(x)
        self.dc.postboxp.Clear()
    
        #except:
        #    print 'erreur dunlog'


    def bakPath(self,event):
        global path
        desktop_pidl = shell.SHGetFolderLocation (0, shellcon.CSIDL_DESKTOP, 0, 0)
        pidl, display_name, image_list = shell.SHBrowseForFolder (
          win32gui.GetDesktopWindow (),
          desktop_pidl,
          "Choissez un repertoire",
          0,
          None,
          None
        )
        if shell.SHGetPathFromIDList (pidl)=="":
          mes.set("aucun repertoire selectionne")
          path=""
        else:path=shell.SHGetPathFromIDList (pidl)
        self.dc.bakpath.SetValue(path)
        
    def dreinit(self):
        global dossier
        for x in range(1,int(dossier['nombre'])+1):
            posy=(int(x)*10)
            idx='480'+str(x)
            self.dc.box[x]=wx.CheckBox(self.dc.panelp,int(idx),label=str(dossier['path',int(x)]))
            self.dc.postboxp.Add(self.dc.box[x],wx.LEFT)
            self.dc.box[x].Bind(wx.EVT_CHECKBOX, self.OnDossierCheck)

    def DShow(self):
        self.dc.DrawText("Choisissez les dossiers à surveiller :",10,30)
    
    def Draw(self):
        global dossier,explorer,path,logfull
        self.dc.SetFont(self.font)
        self.dc.font1 = wx.Font(8, wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_NORMAL, False)
       #wx.NullColour)
        #self.dc.SetTextForeground()
        self.dc.SetFont(self.dc.font1)
        self.dc.DrawText("Choisissez les dossiers à surveiller :",10,30)
        self.dc.panelp=scrolled.ScrolledPanel(self,-1,(10,50),(100,100), style=wx.SUNKEN_BORDER)
        self.dc.panelp.SetupScrolling(scroll_x=True,scroll_y=True)
        self.dc.panelp.SetBackgroundColour('#EAEAE9')
        self.dc.DrawBitmap(self.fond, 10, 300, True)
        #self.dc.panel=MyScrollPanel(self.dc)
        self.dc.postboxp=wx.BoxSizer(wx.VERTICAL)
        self.dc.box={}
        for x in range(1,int(dossier['nombre'])+1):
            #print x
            posy=(int(x)*10)
            idx='480'+str(x)
            self.dc.box[x]=wx.CheckBox(self.dc.panelp,int(idx),label=str(dossier['path',int(x)]))
            self.dc.postboxp.Add(self.dc.box[x],wx.LEFT)
            self.dc.box[x].Bind(wx.EVT_CHECKBOX, self.OnDossierCheck)
        self.dc.panelp.SetSizer(self.dc.postboxp)
        self.dc.postboxp.FitInside(self.dc.panelp)
        self.dc.panel = wx.Panel ( self,-1,(10,170),(50,100), style=wx.SUNKEN_BORDER)
        self.dc.panel.SetBackgroundColour('#EAEAE9')
        self.dc.sizer = wx.GridBagSizer ( 2, 1 )
        self.dc.message = wx.StaticText(self.dc.panel, -1, '')
        self.dc.newdir = wx.Button ( self.dc.panel, 100, 'Nouveau Dossier' )
        self.dc.newdir.Bind(wx.EVT_BUTTON, self.newDir )
        self.dc.nodir = wx.Button ( self.dc.panel, 100, 'Retirer Dossier' )
        self.dc.nodir.Bind(wx.EVT_BUTTON, self.dirDelete )
        self.dc.sizer.Add ( self.dc.message, ( 1, 0 ) )
        self.dc.sizer.Add ( self.dc.nodir, ( 2, 0 ) )
        self.dc.sizer.Add ( self.dc.newdir, ( 2, 1 ) )
        self.dc.horizontal = wx.BoxSizer ( wx.HORIZONTAL )
        self.dc.horizontal.Add ( ( 0, 0 ), 1 )
        self.dc.horizontal.Add ( self.dc.sizer )
        self.dc.horizontal.Add ( ( 0, 0 ), 1 )
        self.dc.vertical = wx.BoxSizer ( wx.VERTICAL )
        self.dc.vertical.Add ( ( 0, 0, ), 1 )
        self.dc.vertical.Add ( self.dc.horizontal, 0, wx.ALIGN_CENTER )
        self.dc.vertical.Add ( ( 0, 0 ), 1 )
        self.dc.panel.SetSizerAndFit ( self.dc.vertical )
        self.dc.paneld = wx.Panel ( self,-1,(150,50),(250,100), style=wx.SUNKEN_BORDER)
        self.dc.paneld.SetBackgroundColour('#EAEAE9')
        self.dc.explorer=wx.CheckBox(self.dc.paneld,479,label="ne pas superviser les accès de l'explorer")
        self.dc.explorer.Bind(wx.EVT_CHECKBOX, self.OnExplorerCheck)
        self.dc.bakpath=wx.TextCtrl(self.dc.paneld, 2859, value=path,size=(85, -1),pos=(10,20))
        self.dc.bakpath.Bind(wx.EVT_TEXT, self.OnPathSelect)
        self.dc.bakpath.SetValue(path)
        self.dc.libellebakpath=wx.StaticText(self.dc.paneld, -1, label="Répertoire de backup \n du log de sécurité",pos=(10,48))
        self.dc.libellebakpath.SetBackgroundColour('#EAEAE9')
        self.dc.nodir = wx.Button ( self.dc.paneld, 100, 'Dossier',pos=(100,20) )
        self.dc.nodir.Bind(wx.EVT_BUTTON, self.bakPath )
        self.dc.logfull=wx.CheckBox(self.dc.paneld,480,label="sauvegarder l'intégralité du log de sécurité",pos=(10,80))
        self.dc.logfull.Bind(wx.EVT_CHECKBOX, self.OnLogFullCheck)
        self.dc.explorer.SetValue(explorer)
        self.dc.logfull.SetValue(logfull)
        self.Show ( True )
        
    def OnPaint(self, event):
        global postes,users,dc,box,panelp

        wx.BufferedPaintDC(self,self.bitmap)
        self.chargeDossier()
        self.Draw()
        event.Skip()



    def saveConfig(self):
        global i,root,UserButton,dvariable,explorer,path,logfull,message
        message="erreur sauvegarde"
        try:
            chemFS= oscurdir + os.sep + "wok"+os.sep+ "conf"+os.sep+"resap.gwh"
            logfile = open(chemFS,'rb')
            zero=False
        except:
            chemFS= oscurdir + os.sep + "wok"+os.sep+ "need"+os.sep+"zero.gwh"
            logfile = open(chemFS,'rb')
            chemFS= oscurdir + os.sep + "wok"+os.sep+ "conf"+os.sep+"resap.gwh"
            zero=True
        def Gdecrypt(outputin,result):
            xdecryptor=AES.new(str(ElChaloR[0:24]), AES.MODE_CBC,jak)
            chunksize=(64*1024)
            rep=''
            while True:
                chunk=''
                chunk=outputin.read(n=chunksize)
                if len(chunk)==0:
                    break
                elif len(chunk)%16!=0:
                    chunk += ' ' * (16-len(chunk) % 16 )
                rep=rep+xdecryptor.decrypt(chunk)
            logfile.close()
            result.write(rep)
            return result
        def Gencrypt(results,outputfile):
            encryptor=AES.new(str(ElChaloR[0:24]), AES.MODE_CBC,jak)
            #decryptor=AES.new(str(ElChaloR[0:24]), AES.MODE_CBC,jak)
            chunksize=(64*1024)
            mlogfile = open(outputfile, 'wb')
            ret=''
            while True:
                chunk = results.read(n=chunksize)
                if len(chunk)==0:
                    break
                elif len(chunk)%16!=0:
                    chunk += ' ' * (16-len(chunk) % 16 )                
                ret=ret+chunk
            djunky=encryptor.encrypt(ret)
            mlogfile.write(djunky)
            mlogfile.close()
        class TransPak:
            def write(self,data):
                outputin.write(data.encode('utf-8'))
        outputin = StringIO.StringIO(logfile.read())
##                        outputin.write(logfile.read())
        result = StringIO.StringIO()
        #detr=obj.decrypt(outputin.getvalue())
        Gdecrypt(outputin,result)
        outputin.close()
        #result.write(detr)
        drunk=result.getvalue()
        result.close()
        lou=len(drunk)
        drink=''
        #print repr(drunk)
        for c in range(0,lou):
            try:
                if drunk[c:c+7]=='</PrsP>':
                    drink=drink+'</PrsP>'
                    break
                else:drink=drink+drunk[c]
            except:
                pass
        #print repr(drink)
        xim=xml.dom.minidom.parseString(drink)
        logfile.close()

        racine=xim.documentElement
        if zero==True:
            element =xim.createElement("EXPLORER")
            element.setAttribute("VALUE",str(explorer))
            racine.appendChild(element)
            element =xim.createElement("BACKPATH")
            element.setAttribute("PATH",str(path))
            element =xim.createElement("LOGFULL")
            element.setAttribute("VALUE",str(logfull))
            racine.appendChild(element)
        elif zero==False:
            try:
                xorb=False
                unem = xim.getElementsByTagName('EXPLORER')
                for unam in unem:
                    unam.setAttribute("VALUE",str(explorer))
                    xorb=True
                if xorb==False:
                    element =xim.createElement("EXPLORER")
                    element.setAttribute("VALUE",str(explorer))
                    racine.appendChild(element)                    
            except:
                element =xim.createElement("EXPLORER")
                element.setAttribute("VALUE",str(explorer))
                racine.appendChild(element)

            try:
                nunem = xim.getElementsByTagName('BACKPATH')
                xorb=False
                for nunam in nunem:
                    nunam.setAttribute("PATH",str(path))
                    xorb=True
                if xorb==False:
                    element =xim.createElement("BACKPATH")
                    element.setAttribute("PATH",str(path))
                    racine.appendChild(element)                  
            except:
                element =xim.createElement("BACKPATH")
                element.setAttribute("PATH",str(path))
                racine.appendChild(element)
            try:
                xorb=False
                pnunem = xim.getElementsByTagName('LOGFULL')                
                for pnunam in pnunem:
                    pnunam.setAttribute("VALUE",str(logfull))
  
                    xorb=True
                if xorb==False:

                    element =xim.createElement("LOGFULL")
                    element.setAttribute("VALUE",str(logfull))
                    racine.appendChild(element)

            except:

                element =xim.createElement("LOGFULL")
                element.setAttribute("VALUE",str(logfull))
                racine.appendChild(element)
            message="changements sauvegardés"



        outputin = StringIO.StringIO()
        xim.writexml(TransPak(),encoding='utf-8')
        results = StringIO.StringIO(outputin.getvalue())
        Gencrypt(results,chemFS)
        outputin.close()
        results.close()
        self.Destroy()



        
    def OnLeftDown(self, event):
        global message,vtp,line1,line2,line3,reset
        #self.bdc = wx.BufferedDC(self.cdc)
        pos = event.GetPosition()
##        self.dc.nkey.SelectAll()
##        self.key = self.dc.nkey.GetValue()
##        self.dc.nkey.Clear()
#        print "+"+repr(self.key)+"+"
        if self.closeRegion.ContainsPoint(pos):
            self.Close()
        elif self.validRegion.ContainsPoint(pos):
            wx.BufferedDC(wx.ClientDC(self),self.valida)
            try:
                self.saveConfig()
                try:
                        reset=True
                        line1="Configuration enregistrée."
                        line2="Relancer le programme"
                        line3="pour la prendre en compte"
                        self.Close()
                        WizardEnd(None, 464, 'Chronos Monitor Dossier')
                except:
                    self.dc.message.SetLabel(message)
            except:
                self.dc.message.SetLabel(message)
        x, y = self.ClientToScreen(event.GetPosition())
        ox, oy = self.GetPosition()
        dx = x - ox
        dy = y - oy
        self.delta = ((dx, dy))


    def OnMouseMove(self, event):
        global enter,line1,line2,line3
        pos = event.GetPosition()
        if self.closeRegion.ContainsPoint(pos):
            wx.BufferedDC(wx.ClientDC(self),self.closer)
            self.DShow()
            enter=True
        elif self.validRegion.ContainsPoint(pos):
            wx.BufferedDC(wx.ClientDC(self),self.validr)
            self.DShow()
            enter=True
        else:
            if enter==True:
                wx.BufferedDC(wx.ClientDC(self),self.bitmap)
                self.DShow()
                enter=False          

        if event.Dragging() and event.LeftIsDown():
            x, y = self.ClientToScreen(event.GetPosition())
            fp = (x - self.delta[0], y - self.delta[1])
            self.Move(fp)
        #print enter
        event.Skip()


class Options(wx.Frame):
    global enter,dusers,line1,line2,line3
    def __init__(self, parent, id, title):
        global enter,dusers,line1,line2,line3
        wx.Frame.__init__(self, parent, id, title, size=(250, 150),style=wx.FRAME_SHAPED |wx.FRAME_NO_TASKBAR|wx.NO_BORDER)

        self.font = wx.Font(11, wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL, 
		wx.FONTWEIGHT_BOLD, False, 'Comic Sans MS')

        #self.panel=wx.Panel(self,-1)

        self.hasShape=False
        self.delta=(0,0)

        self.image_file = 'img/option_0.gif'
        self.bmp = wx.Bitmap(self.image_file, wx.BITMAP_TYPE_GIF)
        #bg=wx.StaticBitmap(self.panel, wx.ID_ANY, bmp, (0, 0))
        
        self.bitmap = wx.Bitmap('img/option_0.png', wx.BITMAP_TYPE_PNG)
        self.wizard = wx.Bitmap('img/wizard-normal.png', wx.BITMAP_TYPE_PNG)
        self.wizarda = wx.Bitmap('img/option_ass_appui.png', wx.BITMAP_TYPE_PNG)
        self.wizardr = wx.Bitmap('img/option_ass_rollover.png', wx.BITMAP_TYPE_PNG)
        self.usersa = wx.Bitmap('img/option_ge_appui.png', wx.BITMAP_TYPE_PNG)
        self.usersr = wx.Bitmap('img/option_ge_rollover.png', wx.BITMAP_TYPE_PNG)
        self.dossiersa = wx.Bitmap('img/option_su_appui.png', wx.BITMAP_TYPE_PNG)
        self.dossiersr = wx.Bitmap('img/option_su_rollover.png', wx.BITMAP_TYPE_PNG)
        self.closer = wx.Bitmap('img/option_close_rollover.png', wx.BITMAP_TYPE_PNG)
        self.analysea = wx.Bitmap('img/option_an_appui.png', wx.BITMAP_TYPE_PNG)
        self.analyser = wx.Bitmap('img/option_an_rollover.png', wx.BITMAP_TYPE_PNG)
        self.parama = wx.Bitmap('img/option_para_appui.png', wx.BITMAP_TYPE_PNG)
        self.paramr = wx.Bitmap('img/option_para_rollover.png', wx.BITMAP_TYPE_PNG)
        self.wizard = wx.Bitmap('img/wizard-normal.png', wx.BITMAP_TYPE_PNG)
        self.users = wx.Bitmap('img/users-normal.png', wx.BITMAP_TYPE_PNG)
        self.dossiers = wx.Bitmap('img/dossiers-normal.png', wx.BITMAP_TYPE_PNG)
        self.close = wx.Bitmap('img/close-normal.png', wx.BITMAP_TYPE_PNG)
        self.analyse = wx.Bitmap('img/dossiers-normal.png', wx.BITMAP_TYPE_PNG)
        self.param = wx.Bitmap('img/para_0.png', wx.BITMAP_TYPE_PNG)
        
        
        #bmp = wx.Bitmap(image_file)
        #self.bg=wx.StaticBitmap(self, wx.ID_ANY, bmp, (0, 0))
        self.SetClientSize((self.bitmap.GetWidth(), self.bitmap.GetHeight()))

        if wx.Platform == '__WXGTK__':
            self.Bind(wx.EVT_WINDOW_CREATE, self.SetNoteShape)
        else: self.SetNoteShape()


        enter=False         
        #MyButton(self.panel,-1,(47,168),'img/sync-normal.png','img/sync-rollover.png','img/appui-sync.png')
        #self.SetTransparent(220)
        self.Bind(wx.EVT_PAINT, self.OnPaint)
        self.Bind(wx.EVT_LEFT_DOWN, self.OnLeftDown)
        self.Bind(wx.EVT_LEFT_DOWN, self.OnLeftDown)
        self.Bind(wx.EVT_MOTION, self.OnMouseMove)

        self.bitmapRegion = wx.RegionFromBitmap(self.bitmap)
        self.wizardRegion = wx.RegionFromBitmap(self.wizard)
        self.usersRegion = wx.RegionFromBitmap(self.users)
        self.dossiersRegion = wx.RegionFromBitmap(self.dossiers)
        self.closeRegion = wx.RegionFromBitmap(self.close)
        self.analyseRegion = wx.RegionFromBitmap(self.analyse)
        self.paramRegion = wx.RegionFromBitmap(self.param)


        self.wizardRegion.IntersectRegion(self.bitmapRegion)
        self.wizardRegion.Offset(22, 60)

        self.usersRegion.IntersectRegion(self.bitmapRegion)
        self.usersRegion.Offset(22, 92)

        self.dossiersRegion.IntersectRegion(self.bitmapRegion)
        self.dossiersRegion.Offset(22, 130)  

        self.closeRegion.IntersectRegion(self.bitmapRegion)
        self.closeRegion.Offset(201, 12)

        self.analyseRegion.IntersectRegion(self.bitmapRegion)
        self.analyseRegion.Offset(22, 170)

        self.paramRegion.IntersectRegion(self.bitmapRegion)
        self.paramRegion.Offset(117, 252)        
      

        self.dc = wx.ClientDC(self)
        self.dc.DrawBitmap(self.bitmap, 0, 0, True)
        self.Show(True)
        self.Fit()
        #self.panel=wx.Panel(self,-1)
        #bg=wx.StaticBitmap(self.panel, wx.ID_ANY, bmp, (0, 0))
        #MyButton(self,-1,(49,168),'img/sync-normal.png','img/sync-rollover.png','img/appui-sync.png')




    def OnClose(self, event):
        self.tskic.Destroy()
        self.Destroy()


    def SetNoteShape(self, *event):
        #region=wx.RegionFromBitmapColour(self.bitmap,'#000000',0)
        region = wx.RegionFromBitmap(self.bmp)
        self.hasShape=self.SetShape(region)


    def OnClicked(self, event):
        #print 'event reached frame class'
        event.Skip()
    def Draw(self):
        self.dc.SetFont(self.font)
        self.dc.SetTextForeground('WHITE')        

    def OnPaint(self, event):
        wx.BufferedPaintDC(self,self.bitmap)
        self.Draw()
        #panel=
        #MyBG(self,-1)
        #panel = MyPanel(self, -1)
        #MyButton(self,-1,(49,168),'img/sync-normal2.png','img/sync-rollover2.png','img/appui-sync2.png')
##        self.dc.DrawBitmap(self.bitmap, 0, 0, True)
##        self.dc.DrawBitmap(self.close, 201, 12, True)
##        self.dc.sincro=self.dc.DrawBitmap(self.sync, 51, 168, True)
        #self.oversincro=self.dc.DrawBitmap(self.oversync, 51, 168, True)
        #self.oversincro.Hide()
##        self.dc.DrawBitmap(self.wizard, 22, 40, True)
##        self.dc.DrawBitmap(self.users, 22, 80, True)
##        self.dc.DrawBitmap(self.dossiers, 22, 120, True)
##        self.dc.DrawBitmap(self.analyse, 22, 160, True)
        #self.dc.DrawBitmap(self.reduce, 180, 45, True)
        #self.sync.Bind(wx.EVT_ENTER,self.OnSync)
        #MyButton(self.dc,-1,(51,168),'img/sync-normal2.png','img/sync-rollover2.png','img/appui-sync2.png')
        event.Skip()

        





    def OnLeftDown(self, event):
        global line1,line2,line3
        pos = event.GetPosition()
        if self.closeRegion.ContainsPoint(pos):
            self.Close()
        elif self.wizardRegion.ContainsPoint(pos):
            wx.BufferedDC(wx.ClientDC(self),self.wizarda)
            if dusers['active']==False:
                try:
                    wizardframe = wx.FindWindowById(463)
                    if wizardframe.IsShown():
                        wizardframe.Show()
                except:WizardActivation(None, 463, 'Chronos Monitor Wizard')           
            elif dusers['config']=="0" :
                line1="action non autorisée"
                line2="demandez l'autorisation" 
                line3="à votre administrateur"
                try:
                    dialogframe = wx.FindWindowById(465)
                    dialogframe.Close()
                    WizardEnd(None, 465, 'Chronos Monitor Configuration')            
                except:
                    WizardEnd(None, 465, 'Chronos Monitor Configuration')
            else: 
                try:
                    wizardframe = wx.FindWindowById(463)
                    if wizardframe.IsShown():
                        wizardframe.Show()
                except:WizardActivation(None, 463, 'Chronos Monitor Wizard')
        elif self.usersRegion.ContainsPoint(pos):
            wx.BufferedDC(wx.ClientDC(self),self.usersa)
            if dusers['active']==False:
                line1="veuillez d'abord"
                line2="réaliser le wizard" 
                line3="pour configurer votre poste"
                try:
                    dialogframe = wx.FindWindowById(465)
                    dialogframe.Close()
                    WizardEnd(None, 465, 'Chronos Monitor Configuration')            
                except:
                    WizardEnd(None, 465, 'Chronos Monitor Configuration')            
            elif dusers['config']=="0" :
                line1="action non autorisée"
                line2="demandez l'autorisation" 
                line3="à votre administrateur"
                try:
                    dialogframe = wx.FindWindowById(465)
                    dialogframe.Close()
                    WizardEnd(None, 465, 'Chronos Monitor Configuration')            
                except:
                    WizardEnd(None, 465, 'Chronos Monitor Configuration')
            else: 
                try:
                    userframe = wx.FindWindowById(462)
                    if userframe.IsShown():
                        userframe.Show()
                except:UserSelect(None, 462, 'Chronos Monitor Utilisateurs')
        elif self.dossiersRegion.ContainsPoint(pos):
            wx.BufferedDC(wx.ClientDC(self),self.dossiersa)
            if dusers['active']==False:
                line1="veuillez d'abord"
                line2="réaliser le wizard" 
                line3="pour configurer votre poste"
                try:
                    dialogframe = wx.FindWindowById(465)
                    dialogframe.Close()
                    WizardEnd(None, 465, 'Chronos Monitor Configuration')            
                except:
                    WizardEnd(None, 465, 'Chronos Monitor Configuration')            
            elif dusers['config']=="0" :
                line1="action non autorisée"
                line2="demandez l'autorisation" 
                line3="à votre administrateur"
                try:
                    dialogframe = wx.FindWindowById(465)
                    dialogframe.Close()
                    WizardEnd(None, 465, 'Chronos Monitor Configuration')            
                except:
                    WizardEnd(None, 465, 'Chronos Monitor Configuration')
            else: 
                try:
                    dosframe = wx.FindWindowById(461)
                    if dosframe.IsShown():
                        dosframe.Show()
                except:Dossiers(None, 461, 'Chronos Monitor Dossiers')
        elif self.analyseRegion.ContainsPoint(pos):
            wx.BufferedDC(wx.ClientDC(self),self.analysea)
            if dusers['active']==False:
                line1="veuillez d'abord"
                line2="réaliser le wizard" 
                line3="pour configurer votre poste"
                try:
                    dialogframe = wx.FindWindowById(465)
                    dialogframe.Close()
                    WizardEnd(None, 465, 'Chronos Monitor Configuration')            
                except:
                    WizardEnd(None, 465, 'Chronos Monitor Configuration')  
            elif dusers['auto']=="0":
                line1="action non autorisée"
                line2="demandez l'autorisation" 
                line3="à votre administrateur"
                try:
                    dialogframe = wx.FindWindowById(465)
                    dialogframe.Close()
                    WizardEnd(None, 465, 'Chronos Monitor Configuration')            
                except:
                    WizardEnd(None, 465, 'Chronos Monitor Configuration')
            else:
                try:
                    anaframe = wx.FindWindowById(460)
                    if anaframe.IsShown():
                        anaframe.Show()
                except:Analyse(None, 460, 'Chronos Monitor Analyse',"Construisez vos filtres")
        elif self.paramRegion.ContainsPoint(pos):
            wx.BufferedDC(wx.ClientDC(self),self.parama)
            if dusers['active']==False:
                line1="veuillez d'abord"
                line2="réaliser le wizard" 
                line3="pour configurer votre poste"
                try:
                    dialogframe = wx.FindWindowById(465)
                    dialogframe.Close()
                    WizardEnd(None, 465, 'Chronos Monitor Configuration')            
                except:
                    WizardEnd(None, 465, 'Chronos Monitor Configuration')            
            elif dusers['config']=="0" and dusers['export']=="0":
                line1="action non autorisée"
                line2="demandez l'autorisation" 
                line3="à votre administrateur"
                try:
                    dialogframe = wx.FindWindowById(465)
                    dialogframe.Close()
                    WizardEnd(None, 465, 'Chronos Monitor Configuration')            
                except:
                    WizardEnd(None, 465, 'Chronos Monitor Configuration')
            else:            
                try:
                    paramframe = wx.FindWindowById(459)
                    if paramframe.IsShown():
                        paramframe.Show()
                except:Parametres(None, 459, 'Chronos Monitor Parametres')
                
        x, y = self.ClientToScreen(event.GetPosition())
        ox, oy = self.GetPosition()
        dx = x - ox
        dy = y - oy
        self.delta = ((dx, dy))


    def OnMouseMove(self, event):
        global enter
        if event.LeftIsDown()==False:
            pos = event.GetPosition()
            if self.closeRegion.ContainsPoint(pos):
                wx.BufferedDC(wx.ClientDC(self),self.closer)
                enter=True
            elif self.wizardRegion.ContainsPoint(pos):
                wx.BufferedDC(wx.ClientDC(self),self.wizardr)
                enter=True
            elif self.usersRegion.ContainsPoint(pos):
                wx.BufferedDC(wx.ClientDC(self),self.usersr) 
                enter=True
            elif self.dossiersRegion.ContainsPoint(pos):
                wx.BufferedDC(wx.ClientDC(self),self.dossiersr)
                enter=True
            elif self.analyseRegion.ContainsPoint(pos):
                wx.BufferedDC(wx.ClientDC(self),self.analyser)
                enter=True
            elif self.paramRegion.ContainsPoint(pos):
                wx.BufferedDC(wx.ClientDC(self),self.paramr)
                enter=True
            else:
                if enter==True:
                    wx.BufferedDC(wx.ClientDC(self),self.bitmap)
                    enter=False

        if event.Dragging() and event.LeftIsDown():
            x, y = self.ClientToScreen(event.GetPosition())
            fp = (x - self.delta[0], y - self.delta[1])
            self.Move(fp)
        #print enter
        event.Skip()        


class Widget(wx.Frame):
    global encodings,tenter,line1,line2,line3,dusers,explorer,fanal,user_id,poste_pid,dossier,reset,ssyncro,deltatrsp,to,fl,cl,jak,filtre,anaprocspathin,anaprocspatheq,anaprocsnamin,anaprocsnameq,anaficpathin,anaficpatheq,anaficnamin,anaficnameq,anafennamin,anafennameq,obj,timerF,timerD,mlogfile,mclogfile,XCstring,XTstring,enter,timer,logfile, resac, bvariable,do,rept,crept,hm,wintexte,win,timec,nombrecliq,processactif,texte,prs,pprocess,powa,mes,starter,oscurdir,computer,logType,verbose,user,poste

    def __init__(self, parent, id, title):
        global encodings,tenter,logfull,logpath,line1,line2,line3,dusers,explorer,fanal,user_id,poste_pid,dossier,reset,ssyncro,deltatrsp,to,fl,cl,jak,filtre,anaprocspathin,anaprocspatheq,anaprocsnamin,anaprocsnameq,anaficpathin,anaficpatheq,anaficnamin,anaficnameq,anafennamin,anafennameq,obj,timerD,timerF,mlogfile,mclogfile,XCstring,XTstring,timer,logfile, resac, bvariable,do,rept,crept,hm,win,texte,timec,nombrecliq,processactif,prs,pprocess,powa,mes,starter,oscurdir,computer,logType,verbose,user,poste


        wx.Frame.__init__(self, parent, id, title, size=(250, 150),style=wx.FRAME_SHAPED |wx.FRAME_NO_TASKBAR|wx.NO_BORDER|wx.FULL_REPAINT_ON_RESIZE)

        self.font = wx.Font(11, wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL, 
		wx.FONTWEIGHT_BOLD, False, 'Comic Sans MS')

        #self.panel=wx.Panel(self,-1)

        self.hasShape=False
        self.delta=(0,0)

        self.image_file = 'img/window.png'
        self.bmp = wx.Bitmap(self.image_file)
        #bg=wx.StaticBitmap(self.panel, wx.ID_ANY, bmp, (0, 0))
        
        self.bitmap = wx.Bitmap('img/window.gif', wx.BITMAP_TYPE_GIF)
        self.cross = wx.Bitmap('img/close-normal.png', wx.BITMAP_TYPE_PNG)
        self.crossover = wx.Bitmap('img/fermer-rollover.png', wx.BITMAP_TYPE_PNG)
        self.reduce = wx.Bitmap('img/close-normal.png', wx.BITMAP_TYPE_PNG)
        self.reduceover = wx.Bitmap('img/minimize-rollover.png', wx.BITMAP_TYPE_PNG)
        self.syncr = wx.Bitmap('img/sync-normal2.png', wx.BITMAP_TYPE_PNG)
        self.sync = wx.Bitmap('img/sync.png', wx.BITMAP_TYPE_PNG)
        self.oversync = wx.Bitmap('img/sync-rollover.png', wx.BITMAP_TYPE_PNG)
        self.onsync = wx.Bitmap('img/sync-appui.png', wx.BITMAP_TYPE_PNG)
        self.loginr = wx.Bitmap('img/login-normal.png', wx.BITMAP_TYPE_PNG)
        self.login = wx.Bitmap('img/login.png', wx.BITMAP_TYPE_PNG)
        self.overlogin = wx.Bitmap('img/login-rollover.png', wx.BITMAP_TYPE_PNG)
        self.onlogin = wx.Bitmap('img/login-appui.png', wx.BITMAP_TYPE_PNG)
        self.logoutr = wx.Bitmap('img/logout-normal.png', wx.BITMAP_TYPE_PNG)
        self.logout = wx.Bitmap('img/logout.png', wx.BITMAP_TYPE_PNG)
        self.overlogout = wx.Bitmap('img/logout-rollover.png', wx.BITMAP_TYPE_PNG)
        self.onlogout = wx.Bitmap('img/logout-appui.png', wx.BITMAP_TYPE_PNG)
        self.options = wx.Bitmap('img/options-normal.png', wx.BITMAP_TYPE_PNG)
        self.overoptions = wx.Bitmap('img/options-rollover.png', wx.BITMAP_TYPE_PNG)
        self.onoptions = wx.Bitmap('img/options-appui.png', wx.BITMAP_TYPE_PNG)
        self.liste = wx.Bitmap('img/liste-normal.png', wx.BITMAP_TYPE_PNG)
        self.overliste = wx.Bitmap('img/liste-rollover.png', wx.BITMAP_TYPE_PNG)
        self.onliste = wx.Bitmap('img/liste-appui.png', wx.BITMAP_TYPE_PNG)
        #image_file = 'img/fond.png'
##        self.crossf = wx.Bitmap('img/close-fond.png', wx.BITMAP_TYPE_PNG)
##        self.syncf = wx.Bitmap('img/sync-fond.png', wx.BITMAP_TYPE_PNG)
##        self.loginf = wx.Bitmap('img/login-fond.png', wx.BITMAP_TYPE_PNG)
##        self.listef = wx.Bitmap('img/liste-fond.png', wx.BITMAP_TYPE_PNG)
##        self.logoutf = wx.Bitmap('img/logout-fond.png', wx.BITMAP_TYPE_PNG)
##        self.reducef = wx.Bitmap('img/minimize-fond.png', wx.BITMAP_TYPE_PNG)
##        self.optionsf = wx.Bitmap('img/options-fond.png', wx.BITMAP_TYPE_PNG)
        
        #bmp = wx.Bitmap(image_file)
        #self.bg=wx.StaticBitmap(self, wx.ID_ANY, bmp, (0, 0))
        self.SetClientSize((self.bitmap.GetWidth(), self.bitmap.GetHeight()))
        fl=1
        cl=1
        if wx.Platform == '__WXGTK__':
            self.Bind(wx.EVT_WINDOW_CREATE, self.SetNoteShape)
        else: self.SetNoteShape()



        def get_main_dir():
            try:
                sys.frozen
            except AttributeError:
                path = sys.argv[0]
            else:
                path = sys.executable
            return os.path.dirname(os.path.abspath(path))

        oscurdir=get_main_dir()
        jour=time.strftime('%d')
        mois=time.strftime('%m')
        annee=time.strftime('%Y')
        pprocess={}
        pr=0
        mes=""
        dusers={}
        dusers['active']=False
        def ifexist(rept):
            try:
                trylogfile = open(rept, mode ='r')
                trylogfile.close()
                return True
            except:
                return False
        rep=oscurdir+os.sep+"wok"+os.sep+"enc"+os.sep+mois+annee+os.sep+annee+mois+jour
        t=0
        r=True
        if os.access(oscurdir+os.sep+"wok"+os.sep+"enc"+os.sep+mois+annee,os.F_OK)==True:
            while r==True:
                t=t+1
                rept=str(rep)+str(t)+'.gwh'
                r=ifexist(rept)
            r=True
            t=0
            while r==True:
                t=t+1
                crept=str(rep)+str(t)+'condensed.gwh'
                r=ifexist(crept)
            #logfile = open(rept, mode ='a+')
            #clogfile = open(crept, mode ='a+')

        else:
            os.mkdir(oscurdir+os.sep+"wok"+os.sep+"enc"+os.sep+mois+annee)
            while r==True:
                t=t+1
                rept=str(rep)+str(t)+'.gwh'
                r=ifexist(rept)
            r=True
            t=0
            while r==True:
                t=t+1
                crept=str(rep)+str(t)+'condensed.gwh'
                r=ifexist(crept)


        starter=True
        resac=""
        texte=''
        win=''
        timec=''
        nombrecliq=0
        winame=""
        nmes={}
        dossier={}
        encodings={}
        fanal={}
        nmes[0,'time']=""
        nmes[0,'mes']=""
        nmes[0,'q']=0
        processactif=""
        powa=False
        prs=0
        enter=False
        tenter=False
        explorer=False
        filtre={}
        hm = pyHook.HookManager()
        anaprocspathin={}
        anaprocspatheq={}
        anaprocsnamin={}
        anaprocsnameq={}
        anaficpathin={}
        anaficpatheq={}
        anaficnamin={}
        anaficnameq={}
        anafennamin={}
        anafennameq={}
        anaprocspathin['count']=0
        anaprocspatheq['count']=0
        anaprocsnamin['count']=0
        anaprocsnameq['count']=0
        anaficpathin['count']=0
        anaficpatheq['count']=0
        anaficnamin['count']=0
        anaficnameq['count']=0
        anafennamin['count']=0
        anafennameq['count']=0

        #MyButton(self.panel,-1,(47,168),'img/sync-normal.png','img/sync-rollover.png','img/appui-sync.png')
        self.SetTransparent(int(deltatrsp))
        self.Bind(wx.EVT_PAINT, self.OnPaint)
        self.Bind(wx.EVT_LEFT_DOWN, self.OnLeftDown)
        self.Bind(wx.EVT_LEFT_DOWN, self.OnLeftDown)
        self.Bind(wx.EVT_MOTION, self.OnMouseMove)

        self.bitmapRegion = wx.RegionFromBitmap(self.bitmap)
        self.crossRegion = wx.RegionFromBitmap(self.cross)
        self.crossoverRegion = wx.RegionFromBitmap(self.cross)
        self.syncRegion = wx.RegionFromBitmap(self.syncr)
        self.loginRegion = wx.RegionFromBitmap(self.loginr)
        self.logoutRegion = wx.RegionFromBitmap(self.logoutr)
        self.optionsRegion = wx.RegionFromBitmap(self.options)
        self.listeRegion = wx.RegionFromBitmap(self.liste)
        self.reduceRegion = wx.RegionFromBitmap(self.reduce)

        self.syncRegion.IntersectRegion(self.bitmapRegion)
        self.syncRegion.Offset(49, 168)

        self.loginRegion.IntersectRegion(self.bitmapRegion)
        self.loginRegion.Offset(117, 146)

        self.logoutRegion.IntersectRegion(self.bitmapRegion)
        self.logoutRegion.Offset(49, 146)  

        self.optionsRegion.IntersectRegion(self.bitmapRegion)
        self.optionsRegion.Offset(132, 260)

        self.listeRegion.IntersectRegion(self.bitmapRegion)
        self.listeRegion.Offset(10, 40)

        self.reduceRegion.IntersectRegion(self.bitmapRegion)
        self.reduceRegion.Offset(178, 40)

        self.crossoverRegion.IntersectRegion(self.bitmapRegion)
        self.crossoverRegion.Offset(192, 40)
        
        self.bitmapRegion.IntersectRegion(self.crossRegion)
        self.bitmapRegion.Offset(192, 40)

        timer=wx.Timer(self, -1)
        self.Bind(wx.EVT_TIMER, self.minuteLoop,timer)

        timerF=wx.Timer(self, -1)
        self.Bind(wx.EVT_TIMER, self.minuteSave,timerF)

        timerD=wx.Timer(self, -1)
        self.Bind(wx.EVT_TIMER, self.minuteLine,timerD)

        jak='2164691737824342'
        
        #def Tstart():
        def startX():
            global ElChalor,jak
            zrept=oscurdir+os.sep+'wok'+os.sep+'need'+os.sep+'zero.gwh'
            logfile = open(zrept, mode ='rb')
            def Gdecrypt(outputin,result):
                xdecryptor=AES.new(str(ElChaloR[0:24]), AES.MODE_CBC,jak)
                chunksize=(64*1024)
                rep=''
                while True:
                    chunk=''
                    chunk=outputin.read(n=chunksize)
                    if len(chunk)==0:
                        break
                    elif len(chunk)%16!=0:
                        chunk += ' ' * (16-len(chunk) % 16 )
                    rep=rep+xdecryptor.decrypt(chunk)
                logfile.close()
                result.write(rep)
                return result
                        
            outputin = StringIO.StringIO(logfile.read())
##                        outputin.write(logfile.read())
            result = StringIO.StringIO()
            #detr=obj.decrypt(outputin.getvalue())
            Gdecrypt(outputin,result)
            #result.write(detr)
            drunk=result.getvalue()
            lou=len(drunk)
            drink=''
            #print repr(drunk)
            for c in range(0,lou):
                try:
                    if drunk[c:c+7]=='</PrsP>':
                        drink=drink+'</PrsP>'
                        break
                    else:drink=drink+drunk[c]
                except:
                    pass
            #print repr(drink)
            xim=xml.dom.minidom.parseString(drink)
##            zrept=oscurdir+os.sep+'wok'+os.sep+'need'+os.sep+'zero.xml'
##            logfile = open(zrept, mode ='r')
##            xim =xml.dom.minidom.parse(logfile)
##            logfile.close()
            return xim
        XTstring=startX()
        XCstring=startX()
        
        self.dc=wx.BufferedDC(wx.ClientDC(self),self.bmp)
        
##        self.dc = wx.ClientDC(self)
##        self.dc.DrawBitmap(self.bitmap, 0, 0, True)

#        self.dc.Clear()
        self.Show(True)
        self.Fit()

        self.tskic = MyTaskBarIcon(self) 
        self.Centre()
        self.Bind(wx.EVT_CLOSE, self.OnClose)
        #obj=DES3.new(str(ElChaloR[0:24]), DES3.MODE_ECB)
        
        #obj=AES.new(str(ElChaloR[0:24]), AES.MODE_CBC,jak)
    def chargeEncodings(self):
        global encodings
        try:
            chemFS= oscurdir + os.sep + "wok"+os.sep+ "need"+os.sep+"encodings.txt"
            lgac = os.stat(chemFS).st_size
            Ficap = open(chemFS, mode ='r')
            resum=True
        except:
            resum='erreur ouverture encodings.txt'
        try:
            posac=0
            n=0
            country={}
            while posac < lgac:                
                    ChaC = Ficap.readline()            
                    encodings["code",n]=""
                    for char in ChaC:
                        if char=='\n':continue
                        encodings["code",n]=encodings["code",n]+char
                    encodings['nombre']=n
                    n+=1
                    posac=Ficap.tell()
            Ficap.close()
            resum=True
        except:
            resum='erreur dans encodings.txt'
        return resum
    def chargeDossier(self):
        global dossier,explorer,logpath,logfull
        try:
            chemFS= oscurdir + os.sep + "wok"+os.sep+ "conf"+os.sep+"resap.gwh"
            logfile = open(chemFS,'rb')
        except:
            chemFS= oscurdir + os.sep + "wok"+os.sep+ "need"+os.sep+"zero.gwh"
            logfile = open(chemFS,'rb')
        def Gdecrypt(outputin,result):
            xdecryptor=AES.new(str(ElChaloR[0:24]), AES.MODE_CBC,jak)
            chunksize=(64*1024)
            rep=''
            while True:
                chunk=''
                chunk=outputin.read(n=chunksize)
                if len(chunk)==0:
                    break
                elif len(chunk)%16!=0:
                    chunk += ' ' * (16-len(chunk) % 16 )
                rep=rep+xdecryptor.decrypt(chunk)
            logfile.close()
            result.write(rep)
            return result
                    
        outputin = StringIO.StringIO(logfile.read())
##                        outputin.write(logfile.read())
        result = StringIO.StringIO()
        #detr=obj.decrypt(outputin.getvalue())
        Gdecrypt(outputin,result)
        #result.write(detr)
        drunk=result.getvalue()
        lou=len(drunk)
        drink=''
        #print repr(drunk)
        for c in range(0,lou):
            try:
                if drunk[c:c+7]=='</PrsP>':
                    drink=drink+'</PrsP>'
                    break
                else:drink=drink+drunk[c]
            except:
                pass
        #print repr(drink)
        xim=xml.dom.minidom.parseString(drink)
        logfile.close()
        racine=xim.documentElement
        unem = xim.getElementsByTagName('DIR')
        x=1
        dossier['nombre']=0
        for unam in unem:
            dossier['path',x]=unam.getAttribute('PATH')
            dossier['nombre']=x
            x+=1
        unem = xim.getElementsByTagName('EXPLORER')
        explorer=False
        for unam in unem:
            explorer=unam.getAttribute('VALUE')
        if explorer=='False':
            explorer=False
        if explorer=='True':
            explorer=True
        punem = xim.getElementsByTagName('BACKPATH')
        logpath=""
        for punam in punem:
            logpath=punam.getAttribute('PATH')
        nunem = xim.getElementsByTagName('EXPLORER')
        logfull=False
        for nunam in nunem:
            logfull=nunam.getAttribute('VALUE')
        if logfull=='False':
            logfull=False
        if logfull=='True':
            logfull=True
    def ReadLog(self,computer, logType="Security", dumpEachRecord = 1):
        global resac,nmes,dossier,fl,nombrecliq,user_id,poste_pid,to,logpath,logfull
    ##    def get_main_dir():
    ##        try:
    ##            sys.frozen
    ##        except AttributeError:
    ##            path = sys.argv[0]
    ##        else:
    ##            path = sys.executable
    ##        return os.path.dirname(os.path.abspath(path))
        datePrefix = time.strftime("%Y%m%d", time.localtime(time.time()))
        fileExists = 1
        retry = 0
        if logpath=="":
            logpath=win32api.GetTempPath()
        while fileExists:
                if retry == 0:
                        index = ""
                else:
                        index = "-%d" % retry
                try:
                        fname = os.path.join(logpath, "%s%s-%s" % (datePrefix, index, logType) + ".evt")
                        os.stat(fname)
                except os.error:
                        fileExists = 0
                retry = retry + 1
    ##    oscurdir=get_main_dir()
    ##    rept=str(oscurdir)+os.sep+'securitylogfile.csv'
    ##    logfile = open(rept, mode ='w+')
    ##    resac=""
        # read the entire log back.
        h=win32evtlog.OpenEventLog(computer, logType)
        numRecords = win32evtlog.GetNumberOfEventLogRecords(h)
        #print "There are %d records" % numRecords
        cont=True
        num=0
        nfile={}
        o=0
        p=0
        q=0
        
        while 1:
            objects = win32evtlog.ReadEventLog(h, win32evtlog.EVENTLOG_BACKWARDS_READ|win32evtlog.EVENTLOG_SEQUENTIAL_READ, 0)
            if not objects:
                break
            for object in objects:
                # get it for testing purposes, but dont print it.
                msg = win32evtlogutil.SafeFormatMessage(object, logType)
                #timob=object.TimeGenerated.Format()
                #timcu=time.strftime('%m/%d/%y %H:%M:%S')
                find=False
                imsg=msg
                found=False
                if logfull==True:
                    find=True
                    flc=str(fl)
                    nbc=str(nombrecliq)
                    timec=str(object.TimeGenerated.Format())
                    Tresac=flc+'#'+timec+'#acces_dossier#'+nbc+'#'+imsg+'#'+'None'+'#'+user_id+'#'+poste_pid+'\n'
                    try:
                        self.Twrite(Tresac)
                    except:
                        print "erreur Twrite"
                        print repr(msg)
                    
                if explorer==False:
                    if 'explorer.exe' in msg or 'EXPLORER.EXE' in msg:
                        find=True

##
##                        if find==False:
                if msg[0:11]=="Handle ferm" and logfull==False:
                    find=True
                    flc=str(fl)
                    nbc=str(nombrecliq)
                    timec=str(object.TimeGenerated.Format())
                    Tresac=flc+'#'+timec+'#acces_dossier#'+nbc+'#'+imsg+'#'+'None'+'#'+user_id+'#'+poste_pid+'\n'
                    try:
                        self.Twrite(Tresac)
                    except:
                        print "erreur Twrite"
                        print repr(msg)

                if find==False:
                    for x in range(1,dossier['nombre']+1):
                        if dossier['path',x] in msg:
                            imsg=msg
                            find=True
                    if find==True:
                        if msg[0:12]=="Objet ouvert" :
                            flc=str(fl)
                            nbc=str(nombrecliq)
                            timec=str(object.TimeGenerated.Format())
                            Tresac=flc+'#'+timec+'#acces_dossier#'+nbc+'#'+imsg+'#'+'None'+'#'+user_id+'#'+poste_pid+'\n'
                            try:
                                self.Twrite(Tresac)
                            except:
                                print "erreur Twrite"
                                print repr(msg)

                                

                num = num + len(objects)
##        if numRecords == num:
##            pass
##            #print "Successfully read all", numRecords, "records"
##        else:
##            print "Couldn't get all records - reported %d, but found %d" % (numRecords, num)
##            print "(Note that some other app may have written records while we were running!)"

        try:
            win32evtlog.ClearEventLog(h, fname)
        except:
            "Couldn't clear event log"
        try:
            win32evtlog.CloseEventLog(h)
        except:
            print "Couldn't close event log"
       

    def Twrite(self,string):
        global rept,XTstring,fl
        try:
            racine=XTstring.documentElement
            element =XTstring.createElement("PrsP")
            element.setAttribute('ReportLine',string)
            racine.appendChild(element)
        finally:
            self.minuteView(string)
            fl+=1
##        outputin = StringIO.StringIO()

    def makeZero(self):
        rept=oscurdir+os.sep+'wok'+os.sep+'need'+os.sep+'zero.xml'
        zrept=oscurdir+os.sep+'wok'+os.sep+'need'+os.sep+'zero.gwh'
        def Gencrypt(results,outputfile):
            encryptor=AES.new(str(ElChaloR[0:24]), AES.MODE_CBC,jak)
            #decryptor=AES.new(str(ElChaloR[0:24]), AES.MODE_CBC,jak)
            chunksize=(64*1024)
            mlogfile = open(outputfile, 'wb')
            ret=''
            while True:
                chunk = results.read(n=chunksize)
                if len(chunk)==0:
                    break
                elif len(chunk)%16!=0:
                    chunk += ' ' * (16-len(chunk) % 16 )                
                ret=ret+chunk
            djunky=encryptor.encrypt(ret)
            mlogfile.write(djunky)
            mlogfile.close()
        class TTransPak:
            def write(self,data):
                outputin.write(data.encode('utf-8'))
        outputin = StringIO.StringIO()
        logfile = open(rept, mode ='r')
        xim =xml.dom.minidom.parse(logfile)
        xim.writexml(TTransPak(), encoding='utf-8')
        results = StringIO.StringIO(outputin.getvalue())        
        Gencrypt(results,zrept)
        outputin.close()
        results.close()        

    def minuteSave(self,event):
        global XTstring,XCstring
        def Gencrypt(results,outputfile):
            encryptor=AES.new(str(ElChaloR[0:24]), AES.MODE_CBC,jak)
            #decryptor=AES.new(str(ElChaloR[0:24]), AES.MODE_CBC,jak)
            chunksize=(64*1024)
            mlogfile = open(outputfile, 'wb')
            ret=''
            while True:
                chunk = results.read(n=chunksize)
                if len(chunk)==0:
                    break
                elif len(chunk)%16!=0:
                    chunk += ' ' * (16-len(chunk) % 16 )                
                ret=ret+chunk
            djunky=encryptor.encrypt(ret)
            mlogfile.write(djunky)
            mlogfile.close()
        class TTransPak:
            def write(self,data):
                outputin.write(data.encode('utf-8'))
        outputin = StringIO.StringIO()
        XTstring.writexml(TTransPak(), encoding='utf-8')
        results = StringIO.StringIO(outputin.getvalue())        
        Gencrypt(results,rept)
        outputin.close()
        results.close()
        outputin = StringIO.StringIO()
        XCstring.writexml(TTransPak(), encoding='utf-8')
        results = StringIO.StringIO(outputin.getvalue())        
        Gencrypt(results,crept)
        outputin.close()
        results.close()
        
    def Cwrite(self,string):
        global crept,XCstring,cl
        try:
            racine=XCstring.documentElement
            element =XCstring.createElement("PrsP")
            element.setAttribute('ReportLine',string)
            racine.appendChild(element)
        finally:
##            if str(syncro)=="True" and start==True:
            self.minuteView(string)
            cl+=1

    def DShow(self):
        self.dc.message.Show()
        self.dc.message.SetValue(unicode(mes))
        self.dc.display.Show()
        
    def verifyConfig(self):
        global deltatrsp,oscurdir,jak,ElChaloR,ssyncro,analyse,question
        def Gdecrypt(output,decoutput):
            global jak,ElChaloR
            xdecryptor=AES.new(str(ElChaloR[0:24]), AES.MODE_CBC,jak)
            chunksize=(64*1024)
            rep=''
            while True:
                chunk=''
                chunk=output.read(n=chunksize)
                if len(chunk)==0:
                    break
                elif len(chunk)%16!=0:
                    chunk += ' ' * (16-len(chunk) % 16 )
                rep=rep+xdecryptor.decrypt(chunk)
            decoutput.write(rep)
            return decoutput
        glorb=False
        try:
            TchemFSF=oscurdir+os.sep+'wok'+os.sep+'conf'+os.sep+'config.gwh'
            fft=open(TchemFSF, mode ='rb')
            output = StringIO.StringIO(fft.read())
            decoutput=StringIO.StringIO()
            fft.close()
            Gdecrypt(output,decoutput)
            lines={}
            p=0
            lines = decoutput.getvalue()
            tsyncro=""
            tanalyse=""
            tquestion=""
            tdeltatrsp=""
            tdinac=""
            for char in lines:
                if char=='\t':
                    p+=1
                    continue
                if char=='\n':
                    glorb=True
                    break
                if p==0:
                    tsyncro=tsyncro+char
                if p==1:
                    tanalyse=tanalyse+char
                if p==2:
                    tquestion=tquestion+char
                if p==3:
                    tdeltatrsp=tdeltatrsp+char
                if p==4:
                    tdinac=tdinac+char

            decoutput.close()
            output.close()
            if glorb==True:
                if tsyncro=="True":ssyncro=True
                else:ssyncro=False
                if tanalyse=="True":analyse=True
                else:analyse=False
                if tquestion=="True":question=True
                else:question=False
                deltatrsp=tdeltatrsp
                dinac=tdinac
                self.SetTransparent(int(deltatrsp))
                self.Show(True)
        except:
            pass


    def minuteLine(self,event):
        global reset,start,ssyncro
        def syncroCheck():
            self.synchro()
        def messageCheck():
            pass
        if reset==True:
            try:
                self.verifyConfig()
                reset=False
            except:
                self.dc.message.SetValue(unicode(mes)+unicode('erreur config'))
        if str(ssyncro)=="True" and start==True:
            pass

##            syncroCheck()
##            try:
##                self.syncroCheck()
##            except:
##                self.dc.message.SetValue(unicode(mes)+unicode('erreur syncro'))
        try:
            messageCheck()
        except:
            self.dc.message.SetValue(unicode(mes)+unicode('erreur connec'))
    
        
    def minuteLoop(self,event):
        global encodings,cl,nombrecliq,texte,computer,logType,verbose,winame,resac,logfile,do,watcher,start,pprocess,prs,processactif
        def unchain(string):
            result=""
            if string:
                x=len(string)            
                for x in range(0,x):
                    if string[x] in ["'",'"']:
                        result=result+" "
                    elif string[x] in ["#"]:
                        pass
                    else:result=result+string[x]
            return result
        try:
            hwnd = win32gui.GetForegroundWindow()
            # we want the desktop window
            objid = pyAA.Constants.OBJID_WINDOW
            # get the object
            ao = pyAA.AccessibleObjectFromWindow(hwnd, objid)
            pr= ao.GetProcessAndThreadID()
            processes = win32process.EnumProcesses()
    ##        c=wmi.WMI()0000
            p=0
    ##        for t in range(0,prs):
    ##            Trmbl=True
    ##            for pid in processes:
    ##                try:
    ##                    if pprocess[t]==pid :Trmbl=False
    ##                except:
    ##                    pass
    ##            if Trmbl==True:
    ##                timec=time.strftime('%m/%d/%y %H:%M:%S')
    ##                resac='#*#'+str(timec)+'\t'+'process end'+'\t'+pprocess['n',t]+'#**#'+'\n'
    ##                self.Twrite(resac)
        finally:
            try:
                for pid in processes:
               
                    pprocess[p]=pid
                    handle = win32api.OpenProcess(win32con.PROCESS_ALL_ACCESS,False, pid)
                    pprocess['n',p]=win32process.GetModuleFileNameEx(handle, 0)
                    if pid in pr:
                        handle = win32api.OpenProcess(win32con.PROCESS_ALL_ACCESS,False, pid)
                        processactif=win32process.GetModuleFileNameEx(handle, 0)
                    prs=p
                    p+=1
            except:
                pass
        #for process in os.getpid():
        
##        for pid in processes:
##          if pid in pr:
##              handle = win32api.OpenProcess(win32con.PROCESS_ALL_ACCESS,False, pid)
##              pname = win32process.GetModuleFileNameEx(handle, 0)
        timec=time.strftime('%m/%d/%y %H:%M:%S')
        trp=True
        while trp:
            for x in range(0,encodings['nombre']+1):
                try:
                    tprocess=unchain(processactif).decode(encodings['code',x],'strict')
                    fen=unchain(ao.Name).decode(encodings['code',x],'strict')
                    encoding=encodings['code',x]
                    trp=False
                    break
                except:
                    pass



        #if (winame!=w.GetWindowText(hwnd) and winame!=''):
        #resac=str(timec)+'\t'+'minute maid'+'\t'+'cliques:'+str(nombrecliq)+'\t'+'keys:'+str(len(texte))+'\t'+str(winame)+'\n'
        resac=str(cl)+'#'+str(timec)+'#'+'minute_maid'+'#'+str(nombrecliq)+'#'+fen+'#'+tprocess+'#'+str(user["ID",int(to)])+'#'+str(poste["PID"])+'#'+str(encoding)+'\n'
        #self.Twrite(resac)
        self.Cwrite(resac)
        nombrecliq=0
        if ssyncro==True:self.ReadLog(computer, logType, verbose > 0)
        #changes={}
        #print 'loopminute'

    def chargeFiltres(self):
        global oscurdir,filtre,message,anaprocspathin,anaprocspatheq,anaprocsnamin,anaprocsnameq,anaficpathin,anaficpatheq,anaficnamin,anaficnameq,anafennamin,anafennameq

        #print "charge filtre 0"
        try:
        #if oscurdir:
            try:
                chemFS= oscurdir + os.sep + "wok"+os.sep+ "conf"+os.sep+"gaors.gwh"
                logfile = open(chemFS,'rb')
            except:
                chemFS= oscurdir + os.sep + "wok"+os.sep+ "need"+os.sep+"zero.gwh"
                logfile = open(chemFS,'rb')
                chemFS= oscurdir + os.sep + "wok"+os.sep+ "conf"+os.sep+"gaors.gwh"
            def Gdecrypt(outputin,result):
                xdecryptor=AES.new(str(ElChaloR[0:24]), AES.MODE_CBC,jak)
                chunksize=(64*1024)
                rep=''
                while True:
                    chunk=''
                    chunk=outputin.read(n=chunksize)
                    if len(chunk)==0:
                        break
                    elif len(chunk)%16!=0:
                        chunk += ' ' * (16-len(chunk) % 16 )
                    rep=rep+xdecryptor.decrypt(chunk)
                logfile.close()
                result.write(rep)
                return result
                        
            outputin = StringIO.StringIO(logfile.read())
    ##                        outputin.write(logfile.read())
            result = StringIO.StringIO()
            #detr=obj.decrypt(outputin.getvalue())
            Gdecrypt(outputin,result)
            #result.write(detr)
            drunk=result.getvalue()
            lou=len(drunk)
            drink=''
            #print repr(drunk)
            for c in range(0,lou):
                try:
                    if drunk[c:c+7]=='</PrsP>':
                        drink=drink+'</PrsP>'
                        break
                    else:drink=drink+drunk[c]
                except:
                    pass
            #print repr(drink) ,filtre,anaprocspathin,anaprocspatheq,anaprocsnamin,anaprocsnameq,anaficpathin,anaficpatheq,anaficnamin,anaficnameq,anafennamin,anafennameq

            xim=xml.dom.minidom.parseString(drink)
            logfile.close()
            unem = xim.getElementsByTagName('FILTRE')
            x=1
            xappi=1
            xafpi=1
            xappe=1
            xafpe=1
            xapne=1
            xafne=1
            xalfne=1
            xapni=1
            xafni=1
            xalfni=1
            
            #print 'charge filtre'

            filtre['nombre']=0
            for unam in unem:
                filtre['Libelle',x]=unam.getAttribute('Libelle')
                filtre['nombre']=x
                filtre['Contenant',x]=unam.getAttribute('Contenant')
                filtre['Propriete',x]=unam.getAttribute('Propriete')
                filtre['Contenu',x]=unam.getAttribute('Contenu')
                filtre['Client',x]=unam.getAttribute('Client')
                filtre['Prestation',x]=unam.getAttribute('Prestation')
                filtre['Prestationid',x]=unam.getAttribute('Prestationid')
                filtre["checked",x]=False
                #print filtre['Contenant',x]
                if unicode(filtre['Contenant',x])==u"Le chemin du processus":
                    if unicode(filtre['Propriete',x])==u"est égal à":
                        anaprocspathin['contenu',xappi]=filtre['Contenu',x]
                        anaprocspathin['client',xappi]=filtre['Client',x]
                        anaprocspathin['prestation',xappi]=filtre['Prestation',x]
                        anaprocspathin['prestationid',xappi]=filtre['Prestationid',x]
                        anaprocspathin['count']=xappi
                        xappi+=1
                    elif unicode(filtre['Contenant',x])==u"contient":
                        anaprocspatheq['contenu',xappe]=filtre['Contenu',x]
                        anaprocspatheq['client',xappe]=filtre['Client',x]
                        anaprocspatheq['prestation',xappe]=filtre['Prestation',x]
                        anaprocspatheq['prestationid',xappe]=filtre['Prestationid',x]
                        anaprocspatheq['count']=xappe
                        xappe+=1
                elif unicode(filtre['Contenant',x])==u"Le nom du processus":
                    if unicode(filtre['Propriete',x])==u"est égal à":
                        anaprocsnamin['contenu',xapni]=filtre['Contenu',x]
                        anaprocsnamin['client',xapni]=filtre['Client',x]
                        anaprocsnamin['prestation',xapni]=filtre['Prestation',x]
                        anaprocsnamin['prestationid',xapni]=filtre['Prestationid',x]
                        anaprocsnamin['count']=xapni
                        xapni+=1
                    elif unicode(filtre['Contenant',x])==u"contient":
                        anaprocsnameq['contenu',xapne]=filtre['Contenu',x]
                        anaprocsnameq['client',xapne]=filtre['Client',x]
                        anaprocsnameq['prestation',xapne]=filtre['Prestation',x]
                        anaprocsnameq['prestationid',xapne]=filtre['Prestationid',x]
                        anaprocsnameq['count']=xapne
                        xapne+=1
                elif unicode(filtre['Contenant',x])==u"Le chemin du fichier":
                    if filtre['Propriete',x]=="est égal à":
                        anaficpathin['contenu',xafpi]=filtre['Contenu',x]
                        anaficpathin['client',xapfi]=filtre['Client',x]
                        anaficpathin['prestation',xafpi]=filtre['Prestation',x]
                        anaficpathin['prestationid',xafpi]=filtre['Prestationid',x]
                        anaficpathin['count']=xafpi
                        xafpi+=1
                    elif unicode(filtre['Propriete',x])==u"contient":
                        anaficpatheq['contenu',xafpe]=filtre['Contenu',x]
                        anaficpatheq['client',xafpe]=filtre['Client',x]
                        anaficpatheq['prestation',xafpe]=filtre['Prestation',x]
                        anaficpatheq['prestationid',xafpe]=filtre['Prestationid',x]
                        anaficpatheq['count']=xafpe
                        xafpe+=1
                elif unicode(filtre['Contenant',x])==u"Le nom du fichier":
                    if unicode(filtre['Propriete',x])=="est égal à":
                        anaficnamin['contenu',xafni]=filtre['Contenu',x]
                        anaficnamin['client',xafni]=filtre['Client',x]
                        anaficnamin['prestation',xafni]=filtre['Prestation',x]
                        anaficnamin['prestationid',xafni]=filtre['Prestationid',x]
                        anaficnamin['count']=xafni
                        xafni+=1
                    elif unicode(filtre['Propriete',x])==u"contient":
                        anaficnameq['contenu',xafne]=filtre['Contenu',x]
                        anaficnameq['client',xafne]=filtre['Client',x]
                        anaficnameq['prestation',xafne]=filtre['Prestation',x]
                        anaficnameq['prestationid',xafne]=filtre['Prestationid',x]
                        anaficnameq['count']=xafne
                        xafne+=1
                elif unicode(filtre['Contenant',x])==u"Le libellé de la fenêtre":
                    #print 'libelle de la fenetre'
                    if unicode(filtre['Propriete',x])==u"est égal à":
                        anafennamin['contenu',xalfni]=filtre['Contenu',x]
                        anafennamin['client',xalfni]=filtre['Client',x]
                        anafennamin['prestation',xalfni]=filtre['Prestation',x]
                        anafennamin['prestationid',xalfni]=filtre['Prestationid',x]
                        anafennamin['count']=xalfni
                        xalfni+=1
                    elif unicode(filtre['Propriete',x])==u"contient":
                        #print 'libelle de la fenetre contient',filtre['Contenu',x]
                        anafennameq['contenu',xalfne]=filtre['Contenu',x]
                        anafennameq['client',xalfne]=filtre['Client',x]
                        anafennameq['prestation',xalfne]=filtre['Prestation',x]
                        anafennameq['prestationid',xalfne]=filtre['Prestationid',x]
                        anafennameq['count']=xalfne
                        xalfne+=1
                x+=1
        except:
            print "Erreur dans le chargement des filtres"

    def formatFanal(self):
        global fanal
        fanal['client']="None"
        fanal['prestation']="None"

    def analyseLibelle(self,libelle):
        global anafennamin,anafennameq,fanal
        for x in range(1,anafennamin['count']+1):
            if anafennamin['contenu',x]==libelle:
                if unicode(anafennamin['client',x])!=u'non défini':
                    fanal['client']=anafennamin['client',x]
                if unicode(anafennamin['prestation',x])!=u'non défini':
                    fanal['prestation']=anafennamin['prestationid',x]
        for x in range(1,anafennameq['count']+1):
            if anafennameq['contenu',x] in libelle:
                if unicode(anafennameq['client',x])!=u'non défini':
                    fanal['client']=anafennameq['client',x]
                if unicode(anafennameq['prestation',x])!=u'non défini':
                    fanal['prestation']=anafennameq['prestationid',x]

#analyseProcessus(procs),analyseLibelle(libelle),analyseFichier(fichier)

    def analyseProcessus(self,procs):
        global anaprocspathin,anaprocspatheq,anaprocsnamin,anaprocsnameq,fanal
        path=procs
        d=len(path)
        processpath=''
        processfile=''
        u=d
        for x in range(1,d+1):
            b=int(d)-int(x)
            f=b
            f+=1
            if path[b:f]=='\\':
                Trmbl=True
                u=int(d)-int(x)
                break
            processfile=processfile+path[b:f]
        processpath=path[0:u]   
        for x in range(1,anaprocspathin['count']+1):
            if anaprocspathin['contenu',x]==processpath:
                if unicode(anaprocspathin['client',x])!=u'non défini':
                    fanal['client']=anaprocspathin['client',x]
                if unicode(anaprocspathin['prestation',x])!=u'non défini':
                    fanal['prestation']=anaprocspathin['prestationid',x]
        for x in range(1,anaprocspatheq['count']+1):
            if anaprocspatheq['contenu',x] in processpath:
                if unicode(anaprocspatheq['client',x])!=u'non défini':
                    fanal['client']=anaprocspatheq['client',x]
                if unicode(anaprocspatheq['prestation',x])!=u'non défini':
                    fanal['prestation']=anaprocspatheq['prestationid',x]
        for x in range(1,anaprocsnamin['count']+1):
            if anaprocsnamin['contenu',x]==processfile:
                if unicode(anaprocsnamin['client',x])!=u'non défini':
                    fanal['client']=anaprocsnamin['client',x]
                if unicode(anaprocsnamin['prestation',x])!=u'non défini':
                    fanal['prestation']=anaprocsnamin['prestationid',x]
        for x in range(1,anaprocsnameq['count']+1):
            if anaprocsnameq['contenu',x] in processfile:
                if unicode(anaprocsnameq['client',x])!=u'non défini':
                    fanal['client']=anaprocsnameq['client',x]
                if unicode(anaprocsnameq['prestation',x])!=u'non défini':
                    fanal['prestation']=anaprocsnameq['prestationid',x]


    def analyseFichier(self,fichier):
        global anaficpathin,anaficpatheq,anaficnamin,anaficnameq,fanal
        d=len(fichier)
        filepath=''
        filefile=''
        u=d
        for x in range(1,d+1):
            deb=int(d)-int(x)
            fin=deb
            fin+=1
            if fichier[deb:fin]=='\\':
                Trmbl=True
                u=int(d)-int(x)
                break
            filefile=filefile+fichier[deb:fin]
        filepath=fichier[0:u] 
        for x in range(1,anaficpathin['count']+1):
            if anaficpathin['contenu',x]==filepath:
                if unicode(anaficpathin['client',x])!=u'non défini':
                    fanal['client']=anaficpathin['client',x]
                if unicode(anaficpathin['prestation',x])!=u'non défini':
                    fanal['prestation']=anaficpathin['prestationid',x]
        for x in range(1,anaficpatheq['count']+1):
            if anaficpatheq['contenu',x] in filepath:
                if unicode(anaficpatheq['client',x])!=u'non défini':
                    fanal['client']=anaficpatheq['client',x]
                if unicode(anaficpatheq['prestation',x])!=u'non défini':
                    fanal['prestation']=anaficpatheq['prestationid',x]
        for x in range(1,anaficnamin['count']+1):
            if anaficnamin['contenu',x]==filefile:
                if unicode(anaficnamin['client',x])!=u'non défini':
                    fanal['client']=anaficnamin['client',x]
                if unicode(anaficnamin['prestation',x])!=u'non défini':
                    fanal['prestation']=anaficnamin['prestationid',x]
        for x in range(1,anaficnameq['count']+1):
            if anaficnameq['contenu',x] in filefile:
                if unicode(anaficnameq['client',x])!=u'non défini':
                    fanal['client']=anaficnameq['client',x]
                if unicode(anaficnameq['prestation',x])!=u'non défini':
                    fanal['prestation']=anaficnameq['prestationid',x]

            
    def OnClose(self, event):
        self.tskic.Destroy()
        self.Destroy()


    def SetNoteShape(self, *event):
        #region=wx.RegionFromBitmapColour(self.bitmap,'#000000',0)
        region = wx.RegionFromBitmap(self.bitmap)
        self.hasShape=self.SetShape(region)
        
    def OnKey(self,event):
        global powa
        powa=event.GetString()

    def OnClicked(self, event):
        #print 'event reached frame class'
        event.Skip()

    def Draw(self):
        self.dc.SetFont(self.font)
        self.dc.SetTextForeground('WHITE')
        self.dc.display=wx.TextCtrl(self,-1,style= wx.TE_PASSWORD,pos=(60,120))
        self.dc.message=wx.TextCtrl(self,wx.ID_ANY,'',pos=(15,12),size=(188,21))
        #self.dc.nkey=wx.TextCtrl(self,wx.ID_ANY,'',pos=(20,39),size=(180,20))
        self.dc.display.CanPaste()
        self.dc.display.SetEditable(True)
        self.dc.message.SetValue(unicode(mes))
        self.dc.message.SetEditable(False)
        #self.dc.nkey.SetValue("CLEF DACTIVATION")
        self.dc.display.Bind(wx.EVT_TEXT, self.OnKey)
        
    def OnPaint(self, event):
        global timerD
        self.verifyConfig()
        wx.BufferedPaintDC(self,self.bmp)
        self.Draw()
        self.verifyConfig()
        result=self.chargeEncodings()
        if result!=True:
            self.dc.message.SetValue(unicode(result))
        if analyse==True:self.chargeFiltres()
        if ssyncro==True:self.chargeDossier()
        timerD.Start(milliseconds=30000, oneShot=False)
        event.Skip()

    def minuteView(self,line):
        global user,poste
        def unchain(string):
            result=""
            if string:
                x=len(string)            
                for x in range(0,x):
                    if string[x] in ["'",'"']:
                        result=result+" "
                    elif string[x] in ["#"]:
                        pass
                    else:result=result+string[x]
            return result


        def chain(string):
            results=""
            if string:
                x=len(string)            
                for x in range(0,x):
                    if string[x]in ["\\"]:results=results+string[x]+string[x]
                    else:results=results+string[x]
            return results
        Txzorbl={}
        final={}
        ses=0
        p=0
        Txzorbl[p]=""
        ln=len(line)
        for x in range(0,ln):
            char=line[x:x+1]
            if char=="#":
                p+=1
                Txzorbl[p]=""
            else:
                Txzorbl[p]=Txzorbl[p]+char
        try:
            hour=Txzorbl[1]
            dateprem=hour[0:8]
            date='20'+dateprem[6:8]+'/'+dateprem[0:2]+'/'+dateprem[3:5]
            houre=hour[9:18]
            procs=""
            chemin=""
            fen=""
            ncl=0
            datour=str(Txzorbl[1]) 
            inscript=False
            intostr="""INSERT INTO logview (date, heure, nomfenetre, processus, chemin, clicks, client,activite,action,userid,posteid) VALUES """
            if str(Txzorbl[2])=='user_begin':
                ses+=1
                action=Txzorbl[2]
                userid=Txzorbl[3]
                final['session','debut',str(ses)]=datour
                final['session','user',str(ses)]=Txzorbl[4]
                final['session','userid',str(ses)]=Txzorbl[3]
                final['session','postepid',str(ses)]=Txzorbl[5]
                final['session','clicknombr',str(ses)]=0
                intostr=intostr+"('"+date+"','"+ houre+"','"+ fen+"','"+ procs+"','"+chemin + "', '0', '','','debut session','"+final['session','userid',str(ses)]+"','"+final['session','postepid',str(ses)]+"');"
                inscript=True
            if str(Txzorbl[2])=='user_exit':
                action=Txzorbl[2]
                userid=Txzorbl[3]
                final['session','fin',str(ses)]=datour
                final['session','user',str(ses)]=Txzorbl[4]
                final['session','userid',str(ses)]=Txzorbl[3]
                final['session','postepid',str(ses)]=Txzorbl[5]
                intostr=intostr+"('"+date+"','"+ houre+"','"+ fen+"','"+ procs+"','"+chemin+"', '0', '','','fin session','"+final['session','userid',str(ses)]+"','"+final['session','postepid',str(ses)]+"');"
                inscript=True
            if str(Txzorbl[2])=='minute_maid':
                action=Txzorbl[2]
                chemin="None"
                try:
                    userid=Txzorbl[6]
                except:
                    userid=0
                try:
                    postepid=Txzorbl[7]
                except:
                    postepid=poste['PID']
                try:
                    procs=chain(Txzorbl[5])
                except:
                    procs="None"
                try:
                    ncl=0
                    fen=chain(unchain(Txzorbl[4]))
                except:
                    fen="None"
                try:
                    ncl=chain(unchain(Txzorbl[3]))
                except:
                    ncl=0
                intostr=intostr+"('"+date+"','" +houre+"','"+ fen+"','"+ procs+"','"+chemin+"', '"+str(ncl)+"','','','minute_maid','"+userid+"','"+postepid+"');"
                inscript=True 
            if str(Txzorbl[2])=='window_change-mouse':
                action=Txzorbl[2]
                chemin="None"
                try:
                    userid=Txzorbl[6]
                except:
                    userid=0
                try:
                    postepid=Txzorbl[7]
                except:
                    postepid=poste['PID']
                try:
                    procs=chain(Txzorbl[5])
                except:
                    procs="None"
                try:
                    ncl=0
                    fen=chain(unchain(Txzorbl[4]))
                except:
                    fen="None"
                try:
                    ncl=chain(unchain(Txzorbl[3]))
                except:
                    ncl=0
                intostr=intostr+"('"+str(date)+"','" +str(houre)+"','"+ fen+"','"+ procs+"','"+chemin+"','"+str(ncl)+"', '','','"+str(action)+"','"+str(userid)+"','"+str(postepid)+"');"
                inscript=True

            if inscript==True:
                conn_string = "host='88.191.122.246' dbname='chronos-monitor.com' user='user' password='gaor867'"
                conn = psycopg2.connect(conn_string)
                conn.set_client_encoding('UTF8')
                curs = conn.cursor()
                presult=curs.execute("SELECT action FROM logview WHERE posteid='"+poste["PID"]+"';")
                rresult=curs.fetchall()
                if rresult:
                    intostr="UPDATE logview SET date='"+str(date)+"', heure='" +str(houre)+"', nomfenetre='"+ fen+"', processus='"+ procs+"', chemin='"+chemin+"', clicks='"+str(ncl)+"', client='',activite='',action='"+str(action)+"',userid='"+str(userid)+"' WHERE posteid='"+poste["PID"]+"';"
                result=curs.execute(intostr)
                conn.commit()
                curs.close()
                conn.close()
        except:
            pass
                
    def synchro(self):
        global fanal,analyse,mes
        def FicExport(chemr,fic):
            global obj

            tze=0
            rrept=chem
            logfile = open(rrept, mode ='rb')
            def Gdecrypt(outputin,result):
                xdecryptor=AES.new(str(ElChaloR[0:24]), AES.MODE_CBC,jak)
                chunksize=(64*1024)
                rep=''
                while True:
                    chunk=''
                    chunk=outputin.read(n=chunksize)
                    if len(chunk)==0:
                        break
                    elif len(chunk)%16!=0:
                        chunk += ' ' * (16-len(chunk) % 16 )
                    rep=rep+xdecryptor.decrypt(chunk)
                logfile.close()
                result.write(rep)
                return result
                        
            outputin = StringIO.StringIO(logfile.read())
##                        outputin.write(logfile.read())
            result = StringIO.StringIO()
            #detr=obj.decrypt(outputin.getvalue())
            Gdecrypt(outputin,result)
            #result.write(detr)
            drunk=result.getvalue()
            lou=len(drunk)
            drink=''
            for c in range(0,lou):
                try:
                    if drunk[c:c+7]=='</PrsP>':
                        drink=drink+'</PrsP>'
                        break
                    else:drink=drink+drunk[c]
                except:
                    pass
            return drink

        def unchain(string):
            result=""
            if string:
                x=len(string)            
                for x in range(0,x):
                    if string[x] in ["'",'"']:
                        result=result+" "
                    elif string[x] in ["#"]:
                        pass
                    else:result=result+string[x]
            return result

        def tunchain(string):
            result=""
            if string:
                x=len(string)            
                for x in range(0,x):
                    if string[x] in ["'",'"']:
                        pass
                    elif string[x] in ["#"," "]:
                        pass
                    else:result=result+string[x]
            return result

        def chain(string):
            results=""
            if string:
                x=len(string)            
                for x in range(0,x):
                    if string[x]in ["\\"]:results=results+string[x]+string[x]
                    else:results=results+string[x]
            return results

            #self.dc.DrawBitmap(self.syncf, 51, 168, True)

        #self.dc.DrawBitmap(self.onsync, 49, 168, True)
        conn_string = "host='88.191.122.246' dbname='chronos-monitor.com' user='user' password='gaor867'"
        conn = psycopg2.connect(conn_string)
        curs = conn.cursor()
        timec=time.strftime('%m/%d/%y %H:%M:%S')
        hour=timec
        dateprem=hour[0:8]
        date='20'+dateprem[6:8]+'/'+dateprem[0:2]+'/'+dateprem[3:5]
        intostr="SELECT nomfichier, line FROM logmaj where posteid='"+poste["ID"]+"' and type='full'"
        presult=curs.execute(str(intostr))
        presult=curs.fetchall()
        u=0
        p=0
        maj={}
        full=False
        for chains in presult:
            #print chain
            u+=1
            full=True
            maj['fichier',u]=""
            maj['line',u]=""
            maj['type',u]="full"
            for char in chains:
                #print 'ficline='+str(char) + 'p='+str(u)
                if p==0:maj['fichier',u]=maj['fichier',u]+str(char)
                if p==1: maj['line',u]=maj['line',u]+str(char)
                p+=1                
            p=0
        pintostr="SELECT nomfichier, line FROM logmaj where posteid='"+poste["ID"]+"' and type='condensed'"
        ppresult=curs.execute(str(pintostr))
        ppresult=curs.fetchall()
        up=u
        po=0
        cond=False
        for pchains in ppresult:
            #print chain
            up+=1
            cond=True
            maj['fichier',up]=""
            maj['line',up]=""
            maj['type',up]="condensed"
            for char in pchains:
                #print 'ficline='+str(char) + 'p='+str(up)
                if po==0:maj['fichier',up]=maj['fichier',up]+str(char)
                if po==1: maj['line',up]=maj['line',up]+str(char)
                po+=1
            po=0
        curs.close()
        conn.close()
        encdir=os.curdir+os.sep+'wok'+os.sep+'enc'
        self.dc.message.SetValue(unicode(mes)+"-")
        for f in os.listdir(encdir):
            if os.path.isdir(os.path.join(encdir, f)):
                chemr=os.path.join(encdir, f)
                for fic in os.listdir(chemr):
                    if os.path.isfile(os.path.join(chemr, fic)):
                        self.dc.message.SetValue(unicode(mes)+"--")
                        chem=os.path.join(chemr, fic)
                        flo=len(chem)
                        fichier=""
                        for fm in range(0,flo-4):
                            if chem[fm]==os.sep:
                                fichier=""
                            else:
                                fichier=fichier+chem[fm]
                        tze=1
                        rrept=chem
                        xil=len(chem)
                        if xil>13 and str(chem[xil-13:xil])=="condensed.gwh":
                            condfichier=""
                            for fm in range(0,flo-13):
                                if chem[fm]==os.sep:
                                    condfichier=""
                                else:
                                    condfichier=condfichier+chem[fm]
                            

                            if cond==True:
                                namor=condfichier
                                namur=maj['fichier',u]
                                lcd=len(condfichier)
                                lfc=len(maj['fichier',up])
                                ecart=lfc-lcd
                                if ecart<0:
                                    ecur=0-int(ecart)
                                    for x in range(0,ecur):
                                        namur=namur+"0"
                                if ecart>0:
                                    for x in range(0,ecart):
                                        namor=namor+"0"
                                if int(namor) < int(namur)and str(maj['type',up])=='condensed':
                                    continue
                                if str(condfichier)==str(maj['fichier',up])and str(maj['type',up])=='condensed':
                                    tze=int(maj['line',up])+1

                        elif str(chem[xil-4:xil])==".gwh":
                            if full==True:
                                namor=fichier
                                namur=maj['fichier',u]
                                lcd=len(fichier)
                                lfc=len(maj['fichier',u])
                                ecart=lfc-lcd
                                if ecart>0:
                                    for x in range(0,ecart):
                                        namor=namor+"0"
                                if ecart<0:
                                    ecur=0-int(ecart)
                                    for x in range(0,ecur):
                                        namur=namur+"0"
                                if int(namor) < int(namur)and str(maj['type',u])=='full':
                                    continue
                                if (str(fichier)==str(maj['fichier',u]))and (str(maj['type',u])=='full'):
                                    tze=int(maj['line',u])+1


                        drink=FicExport(chemr,fic)
                        #print 'drink=',str(drink)
                        FXTCstring=xml.dom.minidom.parseString(drink)
                        fstr=""
                        lines = FXTCstring.getElementsByTagName('PrsP')
                        x=0
                        lignes={}
                        for line in lines:
                            lignes[x]=line.getAttribute('ReportLine')
                            x+=1
                            #
                                                    
                        z=0
                        p=0
                        ligne={}
                        xzorbl={}
                        ligne[z]=""
                        xzorbl[p,z]=""
                        lip=len(fstr)
                        line=False
##                            print repr(results)
##                            print lip
##                            print '======'
                        results=fstr
                        icar=False
                        i=0
##                            for z in range(0,x-1):
##                                print repr(lignes[z])
                            #for char in lignes[z]:
                                #print char
                        t=x-1
                        for r in range(0,t):
                            line = lignes[r]
                            z=r
                            p=0
                            ligne[z]=""
                            xzorbl[p,z]=""
                            ln=len(line)
                            for x in range(0,ln):
                                char=line[x:x+1]
                                icar=line[x:x+2]
                                if char=="#":
                                    p+=1
                                    if p>i:i=p
                                    xzorbl[p,z]=""
                                else:
                                    ligne[z]=ligne[z]+char
                                    xzorbl[p,z]=xzorbl[p,z]+char


                        ses=0
                        fic=0
                        proc=0
                        procv=0
                        winv=0
                        fen=""
                        procs=""
                        chemin=""
                        date=""
                        houre=""
                        #startr=True
                        final={}
                        nfile={}
                        o=0
                        p=0
                        q=0
                        self.dc.message.SetValue(unicode(mes)+"---")
                        for x in range(0,z):
                            for t in range(0,i):
                                try:
                                    xzorbl[t,x]=str(xzorbl[t,x]).strip()
                                    xzorbl[t,x]=str(xzorbl[t,x]).strip("\r\n")
                                except:
                                    pass
                        #if xil-13>=0:print chem[xil-13:xil]+'-fic'
                        if chem[xil-13:xil]=="condensed.gwh":
                            tip="condensed"
                            intostr="""INSERT INTO logcondensed (date, heure, nomfenetre, processus, chemin, clicks, client,activite,action,userid,posteid) VALUES """
    
                        else:
                            tip="full"
                            intostr="""INSERT INTO logfull (date, heure, nomfenetre, processus, chemin, clicks, client,activite,action,userid,posteid) VALUES """
                        inscript=False
                        for x in range(tze,z+1):
                            #for t in range(0,i):
                            #try:
                            
                            hour=xzorbl[1,x]
                            dateprem=hour[0:8]
                            date='20'+dateprem[6:8]+'/'+dateprem[0:2]+'/'+dateprem[3:5]
                            houre=hour[9:18]
                            datour=str(xzorbl[1,x]) 
                            t=len(intostr)
                            ll=xzorbl[0,x]
                            self.dc.message.SetValue(unicode(mes)+"--------")
##                            if startr == False and intostr[t-1:t]!=',' and if inscript==True:
##                                intostr=intostr+","
##                            if startr==True:
##                                startr=False
                            chemin="None"
                            procs="None"
                            fen="None"
                            if str(xzorbl[2,x])=='user_begin':
                                final['session','debut',str(ses)]=datour
                                final['session','user',str(ses)]=xzorbl[4,x]
                                final['session','userid',str(ses)]=xzorbl[3,x]
                                final['session','postepid',str(ses)]=xzorbl[5,x]
                                final['session','clicknombr',str(ses)]=0
                                if inscript==True:intostr=intostr+",('"+date+"','"+ houre+"','"+ fen+"','"+ procs+"','"+chemin + "', '0', '','','debut session','"+final['session','userid',str(ses)]+"','"+final['session','postepid',str(ses)]+"')"
                                else:intostr=intostr+"('"+date+"','"+ houre+"','"+ fen+"','"+ procs+"','"+chemin + "', '0', '','','debut session','"+final['session','userid',str(ses)]+"','"+final['session','postepid',str(ses)]+"')"
                                inscript=True
                            elif str(xzorbl[2,x])=='user_exit':
                                final['session','fin',str(ses)]=datour
                                final['session','user',str(ses)]=xzorbl[4,x]
                                final['session','userid',str(ses)]=xzorbl[3,x]
                                final['session','postepid',str(ses)]=xzorbl[5,x]
                                if inscript==True:intostr=intostr+",('"+date+"','"+ houre+"','"+ fen+"','"+ procs+"','"+chemin+"', '0', '','','fin session','"+final['session','userid',str(ses)]+"','"+final['session','postepid',str(ses)]+"')"
                                else:intostr=intostr+"('"+date+"','"+ houre+"','"+ fen+"','"+ procs+"','"+chemin+"', '0', '','','fin session','"+final['session','userid',str(ses)]+"','"+final['session','postepid',str(ses)]+"')"
                                inscript=True
                                ses+=1
                            elif str(xzorbl[2,x])=='acces_dossier':
                                msg=xzorbl[4,x]
                                userid=tunchain(xzorbl[6,x])
                                postepid=tunchain(xzorbl[7,x])
                                if msg[0:12]=="Objet ouvert" :
                                    #print repr(msg)
                                    #continue
                                    ut = len(msg)
                                    i=0
                                    o+=1
                                    find=True
                                    nomer =False
                                    nomfichier=""
                                    imager=False
                                    handler=False
                                    procer=False
                                    procs=""
                                    nfile[int(o),'open','file']=""
                                    nfile[o,'open','handleid']=""
                                    nfile[o,'open','process']=""
                                    nfile[o,'open','processid']=""
                                    while i<ut:
            ##                            if msg[i:i+12]=="explorer.exe":
            ##                                find=True
            ##                                break
                                        if msg[i:i+16]=="Nom de l'objet :" or nomer==True:                                        
                                            if nomer ==False:no=i 
                                            nomer=True
                                            nomfichier=nomfichier+msg[i]
                                            if msg[i:i+4]=="    ":
                                                nomer=False
                                                for char in nomfichier:
                                                    if char=='.':
                                                        #print 'open fichier=',msg[int(no)+16:int(i)]
                                                        find=False
                                                        nfile[int(o),'open','file']=msg[int(no)+16:int(i)]
                                                        #imsg=imsg+' \t '
                                            i+=1
                                        elif msg[i:i+22]=="Nom du fichier image :" or imager==True:
                                            if imager==False:im=i
                                            imager=True
                                            #procs=procs+msg[i]
                                            if msg[i:i+4]=="    ":
                                                imager=False
                                                nfile[o,'open','process']=msg[im+22:i]
                                                #print "open process",nfile[o,'open','process']
                                            i+=1
                                        elif msg[i:i+27]=="Identificateur du handle : " or handler==True:
                                            if handler==False:ha=i
                                            handler=True
                                            #imsg=imsg+msg[i]
                                            if msg[i:i+4]=="    ":
                                                handler=False
                                                nfile[o,'open','handleid']=msg[ha+27:i]
                                                #print "open handleid",nfile[o,'open','handleid']
                                            i+=1
                                        elif msg[i:i+20]=="Id. du processus  : " or procer==True:
                                            if procer==False:pr=i
                                            procer=True
                                            #imsg=imsg+msg[i]
                                            if msg[i:i+4]=="    ":
                                                procer=False
                                                nfile[o,'open','processid']=msg[pr+20:i]
                                                #print "open processid",nfile[o,'open','processid']
                                            i+=1
                                        else:
                                            i+=1
                                    
                                    self.formatFanal()
                                    if analyse==True:
                                        self.analyseFichier(nfile[int(o),'open','file'])
                                    if inscript==True:intostr=intostr+",('"+ date+"','" +houre+"','"+ fen+"','"+ chain(nfile[o,'open','process'])+"','"+chain(nfile[int(o),'open','file'])+"','"+str(ncl)+"','"+fanal['client']+"','"+fanal['prestation']+"','fichier ouvert','"+userid+"','"+postepid+"')"    
                                    else:intostr=intostr+"('"+ date+"','" +houre+"','"+ fen+"','"+ chain(nfile[o,'open','process'])+"','"+chain(nfile[int(o),'open','file'])+"','"+str(ncl)+"','"+fanal['client']+"','"+fanal['prestation']+"','fichier ouvert','"+userid+"','"+postepid+"')"    
                                    inscript=True
                                elif msg[0:11]=="Handle ferm" :
                                    p+=1
                                    ut = len(msg)
                                    i=0
                                    find=False
                                    imsg="Fichier ferme : "
                                    nomer =False
                                    imager=False
                                    handler=False
                                    procer=False
                                    nfile[p,'close','handleid']=""
                                    nfile[p,'close','process']=""
                                    nfile[p,'close','processid']=""
                                    nfile[p,'close','handleid']=""
                                    while i<ut:
                                        if msg[i:i+22]=="Nom du fichier image :" or imager==True:
                                            if imager==False:im=i
                                            imager=True
                                            #imsg=imsg+msg[i]
                                            if msg[i:i+4]=="    ":
                                                imager=False
                                                nfile[p,'close','process']=msg[im+22:i]
                                                #print 'close process',nfile[p,'close','process']
                                            i+=1
                                        elif msg[i:i+16]=="Id. du handle : " or handler==True:
                                            if handler==False:ha=i
                                            handler=True
                                            #imsg=imsg+msg[i]
                                            if msg[i:i+4]=="    ":
                                                handler=False
                                                nfile[p,'close','handleid']=msg[int(ha)+16:int(i)]
                                                #print 'close handleid',nfile[p,'close','handleid']
                                            i+=1
                                        elif msg[i:i+19]=="Id. de processus : " or procer==True:
                                            if procer==False:pr=i
                                            procer=True
                                            #imsg=imsg+msg[i]
                                            if msg[i:i+4]=="    ":
                                                procer=False
                                                nfile[p,'close','processid']=msg[pr+19:i]
                                                #print "close processid",nfile[p,'close','processid']
                                            i+=1
                                        else:
                                            i+=1
                                    find=True
                                    for x in range(1,o):
                                        if nfile[x,'open','file']=="":continue
                                        if nfile[x,'open','handleid']==nfile[p,'close','handleid']:
                                            find=False
                                            break
                                    self.formatFanal()
                                    if analyse==True and find==False:
                                        self.analyseFichier(nfile[x,'open','file'])
                                    if find==False:
                                        if inscript==True:intostr=intostr+",('" +date+"','" +houre+"','"+ fen+"','"+ chain(nfile[x,'open','process'])+"','"+chain(nfile[x,'open','file'])+"','"+str(ncl)+"', '"+fanal['client']+"','"+fanal['prestation']+"','fichier ferme','"+userid+"','"+postepid+"')"
                                        else:intostr=intostr+"('" +date+"','" +houre+"','"+ fen+"','"+ chain(nfile[x,'open','process'])+"','"+chain(nfile[x,'open','file'])+"','"+str(ncl)+"', '"+fanal['client']+"','"+fanal['prestation']+"','fichier ferme','"+userid+"','"+postepid+"')"
                                        inscript=True
                            elif str(xzorbl[2,x])=='minute_maid':
                                ncl= unchain(xzorbl[3,x])
                                chemin="None"
                                #final['session','clicknombr',str(ses)]=int(final['session','clicknombr',str(ses)])+int(ncl)
                                Trmbl=False
##                                            xzorbl[4,x]=str(xzorbl[5,x]).strip('\r\n')
##                                            xzorbl[3,x]=str(xzorbl[4,x]).replace('\xe9','e')
##                                            xzorbl[3,x]=str(xzorbl[4,x]).replace("'",' ')
                                for p in range(0,proc):
                                    try:
                                        if final['process','nom',str(p),str(ses)]==xzorbl[5,x]:
                                            if final['process','fin',str(p),str(ses)]=="":
                                                Trmbl=True
                                    except:
                                        pass
                                if Trmbl==False:
                                    proc+=1
                                    final['process','debut',str(proc),str(ses)]=xzorbl[1,x]
                                    final['process','fin',str(proc),str(ses)]=""
                                    final['process','nom',str(proc),str(ses)]=""
                                    final['process','nombre',str(ses)]=proc
                                    procv+=1
                                    final['processview','heure',str(proc),str(ses)]=xzorbl[1,x]
                                    final['processview','nom',str(proc),str(ses)]=xzorbl[5,x]
                                    final['processview','nombre',str(ses)]=procv
                                winv+=1
                                final['windownameview','heure',str(winv),str(ses)]=xzorbl[1,x]
                                final['windownameview','nom',str(winv),str(ses)]=xzorbl[5,x]
                                final['windownameview','nombre',str(ses)]=winv
                                self.formatFanal()
                                if analyse==True:
                                    self.analyseProcessus(xzorbl[5,x])
                                    self.analyseLibelle(xzorbl[4,x])
                                procs=chain(unchain(xzorbl[5,x]))
                                fen=chain(unchain(xzorbl[4,x]))
                                userid=tunchain(xzorbl[6,x])
                                postepid=tunchain(xzorbl[7,x])
                                if inscript==True:intostr=intostr+",('"+date+"','" +houre+"','"+ fen+"','"+ procs+"','"+chemin+"', '"+str(ncl)+"','"+fanal['client']+"','"+fanal['prestation']+"','log','"+userid+"','"+postepid+"')"
                                else:intostr=intostr+"('"+date+"','" +houre+"','"+ fen+"','"+ procs+"','"+chemin+"', '"+str(ncl)+"','"+fanal['client']+"','"+fanal['prestation']+"','log','"+userid+"','"+postepid+"')"
                                inscript=True
                            elif str(xzorbl[2,x])=='process_end':
                                Trmbl=False
                                for p in range(0,proc):
                                    try:
                                        if final['process','nom',str(p),str(ses)]==xzorbl[5,x]:
                                            if final['process','fin',str(p),str(ses)]=="":
                                                final['process','fin',str(p),str(ses)]=xzorbl[1,x]
                                                Trmbl=True
                                    except:
                                        pass
                                    
                                if Trmbl==False:
                                    proc+=1
##                                        final['process','fin',str(proc),str(ses)]=xzorbl[1,x]
##                                        final['process','debut',str(proc),str(ses)]=""
##                                        final['process','nom',str(proc),str(ses)]=xzorbl[5,x]
##                                        final['process','nombre',str(ses)]=proc
                                if procs==xzorbl[4,x]:procs=''
                            #if procs==xzorbl[4,x]:procs=''
                            elif str(xzorbl[2,x])=='window_change-mouse':
                                Trmbl=False
                                chemin="None"
                                try:
                                    if xzorbl[3,x]=="None":
                                        continue
                                except:
                                    pass
                                for p in range(0,proc):
                                    try:
                                        if final['process','nom',str(p),str(ses)]==xzorbl[5,x]:
                                            if final['process','fin',str(p),str(ses)]=="":
                                                Trmbl=True
                                    except:
                                        pass
                                
                                if Trmbl==False:
                                    try:
                                        #xzorbl[5,x]=str(xzorbl[5,x]).strip('\r\n')
                                        proc+=1
                                        final['process','debut',str(proc),str(ses)]=xzorbl[1,x]
                                        final['process','fin',str(proc),str(ses)]=""
                                        final['process','nom',str(proc),str(ses)]=xzorbl[5,x]
                                        final['process','nombre',str(ses)]=proc
                                        procv+=1
                                        final['processview','heure',str(proc),str(ses)]=xzorbl[1,x]
                                        final['processview','nom',str(proc),str(ses)]=xzorbl[5,x]
                                        final['processview','nombre',str(ses)]=procv
                                    except:
                                        pass
                                if xzorbl[2,x] not in ['']:
##                                xzorbl[4,x]=xzorbl[4,x]
##                                        xzorbl[4,x]=xzorbl[4,x].replace('\xe9','e')
##                                        xzorbl[4,x]=xzorbl[4,x].replace("'",' ')
                                    winv+=1
                                    final['windownameview','heure',str(winv),str(ses)]=xzorbl[1,x]
                                    final['windownameview','nom',str(winv),str(ses)]=xzorbl[4,x]
                                    final['windownameview','nombre',str(ses)]=winv
                                self.formatFanal()
                                if analyse==True:
                                    self.analyseProcessus(xzorbl[5,x])
                                    self.analyseLibelle(xzorbl[4,x])
                                try:
                                    userid=tunchain(xzorbl[6,x])
                                except:
                                    userid=0
                                try:
                                    postepid=tunchain(xzorbl[7,x])
                                except:
                                    postepid=poste['PID']
                                try:
                                    procs=chain(xzorbl[5,x])
                                except:
                                    procs="None"
                                try:
                                    ncl=0
                                    fen=chain(unchain(xzorbl[4,x]))
                                except:
                                    fen="None"
                                try:
                                    ncl=chain(unchain(xzorbl[3,x]))
                                except:
                                    ncl=0
                                if inscript==True:intostr=intostr+",('"+str(date)+"','" +str(houre)+"','"+ fen+"','"+ procs+"','"+chemin+"','"+str(ncl)+"','"+fanal['client']+"','"+fanal['prestation']+"','log','"+userid+"','"+postepid+"')"
                                else:intostr=intostr+"('"+str(date)+"','" +str(houre)+"','"+ fen+"','"+ procs+"','"+chemin+"','"+str(ncl)+"','"+fanal['client']+"','"+fanal['prestation']+"','log','"+userid+"','"+postepid+"')"
                                inscript=True
##                                    except:
##                                        print 'erreur mage 01'
##                                except:
##                                    print 'erreur mage 00'
                                self.dc.message.SetValue(unicode(mes)+"----")
                        self.dc.message.SetValue(unicode(mes)+"--------")

                        

                        timec=time.strftime('%m/%d/%y %H:%M:%S')
                        hour=timec
                        dateprem=hour[0:8]
                        date='20'+dateprem[6:8]+'/'+dateprem[0:2]+'/'+dateprem[3:5]
                        intostr=intostr+";"
                        #print intostr
                        #print str(intostr)
                        if inscript:
                            try:
                                conn_string = "host='88.191.122.246' dbname='chronos-monitor.com' user='user' password='gaor867'"
                                conn = psycopg2.connect(conn_string)
                                conn.set_client_encoding('UTF8')
                                curs = conn.cursor()
                                result=curs.execute(intostr)
                                conn.commit()
                                tintostr="""INSERT INTO logmaj (datemaj, nomfichier, type, start,line, posteid, userid)
                                        VALUES
                                        """
                                if tip=='full':
                                    tintostr=str(tintostr)+"('now()','"+str(fichier)+"','"+str(tip)+"','"+str(tze)+"','"+str(ll)+"','"+str(poste["ID"])+"','"+str(user["ID",to])+"');"
                                else:
                                    tintostr=str(tintostr)+"('now()','"+str(condfichier)+"','"+str(tip)+"','"+str(tze)+"','"+str(ll)+"','"+str(poste["ID"])+"','"+str(user["ID",to])+"');"
                                #rint str(tintostr)
                                #print tintostr
                                result=curs.execute(str(tintostr))
                                conn.commit()
                                intostr=""
                                self.dc.message.SetValue(unicode(mes)+u'-synchronisé')
                            except:
                                exceptionType, exceptionValue, exceptionTraceback = sys.exc_info()
                                print "Database connection failed!\n ->%s" % (exceptionValue)
                                #print repr(intostr)
                            
                            curs.close()
                            conn.close()






    def OnLeftDown(self, event):
        global line1,line2,line3,dusers,jak,to,fl,cl,timerF,mlogfile,mclogfile,timer,hm,texte,logfile,resac,obj,win,timec,resac,nombrecliq,processactif,start,user,poste,to,processactif,pprocess,prs,mes,rept,oscurdir,foutputin,fresult,computer,logType,verbose,user_id,poste_pid
        def OnMouseEvent(event):
            global dusers,jak,to,fl,cl,resac,win,nombrecliq,processactif,user,poste,prs,mes
            def unchain(string):
                result=""
                if string:
                    x=len(string)     
                    for x in range(0,x):
                        if string[x] in ["'",'"']:
                            pass
                        else:result=result+string[x]
                return result

            #processEndLog()
##            if (win!=event.WindowName and win!='' and win!="None" and win!="FolderView"):
            win=event.WindowName
            nombrecliq=nombrecliq+1
            timec=time.strftime('%m/%d/%y %H:%M:%S')
            processactif="None"
            # called when mouse events are received
            #print 'click souris'
            #print 'Time:',time.ctime()
            #print 'WindowName:',event.WindowName
            #print 'texte:',texte
            # return True to pass the event to other handlerspy
            hwnd = win32gui.GetForegroundWindow()
            # we want the desktop window
            objid = pyAA.Constants.OBJID_WINDOW
            # get the object
            ao = pyAA.AccessibleObjectFromWindow(hwnd, objid)
            pr= ao.GetProcessAndThreadID()
            processes = win32process.EnumProcesses()
    ##        c=wmi.WMI()0000
            p=0
##            for t in range(0,prs):
##                Trmbl=True
##                for pid in processes:
##                    try:
##                        if pprocess[t]==pid :Trmbl=False
##                    except:
##                        pass
##                if Trmbl==True:
##                    timec=time.strftime('%m/%d/%y %H:%M:%S')
##                    resac=str(fl)+'#'+str(timec)+'#'+'process_end'+'#'+pprocess['n',t]+'#'
##                    self.Twrite(resac)
            for pid in processes:
                try:
                    pprocess[p]=pid
                    handle = win32api.OpenProcess(win32con.PROCESS_ALL_ACCESS,False, pid)
                    pprocess['n',p]=win32process.GetModuleFileNameEx(handle, 0)
                    if pid in pr:
                        handle = win32api.OpenProcess(win32con.PROCESS_ALL_ACCESS,False, pid)
                        processactif=win32process.GetModuleFileNameEx(handle, 0)
                    prs=p
                    p+=1
                except:
                    pass
##            trp=True
##            while trp:
##                for x in range(0,encodings['nombre']+1):
##                    try:
##                        tprocess=unchain(processactif).decode(encodings['code',x],'strict')
##                        fen=unchain(event.WindowName).decode(encodings['code',x],'strict')
##                        encoding=encodings['code',x]
##                        print 'good',encoding
##                        trp=False
##                        break
##                    except UnicodeDecodeError, err:
##                        print 'bad',encodings['code',x]
##                        pass
            try:
                result=chardet.detect(processactif)
                charenc=result['encoding']
                tprocess=unchain(processactif).decode(charenc,'replace')
            except:
                tprocess=unchain(processactif)
            try:
                lib=event.WindowName
                result=chardet.detect(lib)
                charenc=result['encoding']
                fen=unchain(event.WindowName).decode(charenc,'replace')
                encoding=charenc
                print encoding
            except:
                fen=unchain(event.WindowName)
                encoding='error'
                fen="error"
                print "erreur encoding"
            resac=str(fl)+'#'+str(timec)+'#'+'window_change-mouse'+'#'+str(nombrecliq)+'#'+fen+'#'+tprocess+'#'+str(user["ID",int(to)])+'#'+str(poste["PID"])+'#'+str(encoding)+'\n'
            self.Twrite(resac)
            return True 
        pos = event.GetPosition()
        if self.bitmapRegion.ContainsPoint(pos):
            for x in range(458,472):
                try:
                    frame=wx.FindWindowById(x)
                    if frame.IsShown():
                        frame.Close()
                except:
                    pass
            if start ==True:
                hm.UnhookMouse()
                timec=time.strftime('%m/%d/%y %H:%M:%S')
                resac=str(fl)+'#'+timec+'#'+'widget_stop'+'#'+user["ID",int(to)]+'#'+user["nom",to]+'#'+poste["PID"]+'\n'
                self.Twrite(resac)
                resac=str(cl)+'#'+timec+'#'+'widget_stop'+'#'+user["ID",int(to)]+'#'+user["nom",to]+'#'+poste["PID"]+'\n'
                self.Cwrite(resac)
    ##                mlogfile.close()
    ##                mclogfile.close()
                #thm=pyHook.HookManager
                #logfile.close()
                self.minuteSave(self)
                timer.Stop()
                timerF.Stop()
                timerD.Stop()
            self.Close()
        elif self.reduceRegion.ContainsPoint(pos):
            for x in range(458,472):
                try:
                    frame=wx.FindWindowById(x)
                    if frame.IsShown():
                        frame.Hide()
                except:
                    pass
            self.Hide()
        elif self.syncRegion.ContainsPoint(pos):
            wx.BufferedDC(wx.ClientDC(self),self.onsync)
            if start ==True:
                self.synchro()
            else:
                mes="Vous devez d'abord vous loguer"
            
        elif self.loginRegion.ContainsPoint(pos):
    ##            self.dc.DrawBitmap(self.loginf, 112, 138, True)
    ##            self.dc.DrawBitmap(self.syncf, 51, 168, True)
##            self.dc.DrawBitmap(self.sync, 51, 168, True)
            wx.BufferedDC(wx.ClientDC(self),self.onlogin)
            #self.dc.DrawBitmap(self.onlogin, 117, 146, True)

            #try:  
            TchemFSF=oscurdir+os.sep+'wok'+os.sep+'conf'+os.sep+'local.gwh'
            fft=open(TchemFSF, mode ='rb')
            output = StringIO.StringIO(fft.read())
            decoutput=StringIO.StringIO()
            #output.write(fft.read())
            fft.close()
            def Gdecrypt(output,decoutput):
                global jak
                xdecryptor=AES.new(str(ElChaloR[0:24]), AES.MODE_CBC,jak)
                chunksize=(64*1024)
                rep=''
                while True:
                    chunk=''
                    chunk=output.read(n=chunksize)
                    if len(chunk)==0:
                        break
                    elif len(chunk)%16!=0:
                        chunk += ' ' * (16-len(chunk) % 16 )
                    rep=rep+xdecryptor.decrypt(chunk)
                decoutput.write(rep)
                return decoutput
            def unchar(timestring):
                result=""
                i=0
                for char in timestring:
                    if char in ['-',' ',':']:
                        pass
                    else:
                        result=result+str(char)
                        i+=1
                    if i==8:
                        break
                return result 
            Gdecrypt(output,decoutput)
            lines={}
            lines = decoutput.getvalue()
            #print 'lines-'+repr(lines)
            #lo=len(lines)
            #lines = decoutput.readlines()
            #print decoutput.getvalue()
            p=0
            poste={}
            user={}
            l=0
            poste["PID"]=""
            poste["ID"]=""
            poste["posteNAME"]=""
            poste["Date"]=""
            poste["GUID"]=""
            poste["ADMINID"]=""
            T=False
            for char in lines:
                if char=='\t':
                    p+=1
                    continue
                if char=='\n':
                    T=True
                    p=0
                    l+=1
                    user["ID",l]=""
                    user["nom",l]=""
                    user["prenom",l]=""
                    user["login",l]=""
                    user["pass",l]=""
                    user["nombre"]=l
                    continue
                if p==0 and l==0:poste["PID"]=poste["PID"]+char
                if p==1 and l==0:poste["ID"]=poste["ID"]+char
                if p==2 and l==0:poste["posteNAME"]=poste["posteNAME"]+char
                if p==3 and l==0:poste["Date"]=poste["Date"]+char
                if p==4 and l==0:poste["GUID"]=poste["GUID"]+char
                if p==5 and l==0:poste["ADMINID"]=poste["ADMINID"]+char
                if T==True and p==0:user["ID",l]= user["ID",l]+char
                if T==True and p==1:user["nom",l]= user["nom",l]+char
                if T==True and p==2:user["prenom",l]= user["prenom",l]+char
                if T==True and p==3:user["login",l]= user["login",l]+char
                if T==True and p==4:user["pass",l]= user["pass",l]+char
##            for x in range(1,l+1):
##                print user["pass",x]
##            m = md5.new()
##            m.update(powa)
##            print poste["Date"]
##            print time.strftime('%Y-%m-%d %H:%M:%S')

            hash1=MD5.new()
##            hash1.digest_size()=16
##            hash2.digest_size()=16
            found = "not"
            if powa:
                found=False
                hash1.update(powa)
                pass2 = hash1.hexdigest()
                #print 'passé='+pass2
                for x in range(1,l+1):
    ##                pass1 = hashlib.sha1(powa).digest()
    ##                pass2 = hashlib.sha1(pass1).hexdigest()                
                    #print user["pass",x]
                    
                    if pass2==user["pass",x]:
                        user_id=user["ID",x]
                        poste_pid=poste["PID"]
                        to=int(x)
                        found=True
                        #print 'gagne'
            if found==False or str(found) == "not":
                if found==False:
                    mes='erreur identifiant'
                    self.dc.message.SetValue(unicode('erreur identifiant'))
                elif str(found)=="not":
                    mes='entrez votre pass'
                    self.dc.message.SetValue(unicode('entrez votre pass'))
            elif int(unchar(poste["Date"]))<int(unchar(time.strftime('%Y-%m-%d'))):
                #try:
                if poste["Date"]:
                    conn_string = "host='88.191.122.246' dbname='chronos-monitor.com' user='user' password='gaor867'"
                    conn = psycopg2.connect(conn_string)
                    curs = conn.cursor()
                    query2="SELECT id,postename,datefin,activated,guid FROM postes WHERE userid='"+str(poste['ADMINID'])+"';"
                    #print query2
                    try:
                        presult=curs.execute(query2)
                        presult=curs.fetchall()                                                   
                    except:
                        exceptionType, exceptionValue, exceptionTraceback = sys.exc_info()
                        print "Database connection failed!\n ->%s" % (exceptionValue)
                        line3="erreur 88" 
                    if presult:
                        #print 'bingo'
                        postes={}
                        active=True
                        postes['selected']=False
                        regroot=_winreg.HKEY_LOCAL_MACHINE
                        hKey=_winreg.OpenKey(regroot,"SOFTWARE\Microsoft\Cryptography",0,_winreg.KEY_READ)
                        keyvalue, type=_winreg.QueryValueEx(hKey, "MachineGuid")
                        u=1
                        for pchain in presult:
                            postes['ID',u]=""
                            postes['posteNAME',u]=""
                            postes['dateFin',u]=""
                            postes['activated',u]=""
                            postes['guid',u]=""
                            postes['nombre']=u
                            p=0
                            for pchar in pchain:
                                #print pchar
                                if p==0:postes['ID',u]=postes['ID',u]+str(pchar)
                                if p==1:postes['posteNAME',u]=postes['posteNAME',u]+str(pchar)
                                if p==2:postes['dateFin',u]=postes['dateFin',u]+str(pchar)
                                if p==3:postes['activated',u]=postes['activated',u]+str(pchar)
                                if p==4:postes['guid',u]=postes['guid',u]+str(pchar)
                                p+=1
                            if postes['guid',u]==str(keyvalue) and postes['activated',u]=="1":
                                postes['selected']=u
                                u+=1
                            elif postes['activated',u]=="0":
                                u+=1
                        if postes['selected']:
                            if int(unchar(postes['dateFin',postes['selected']]))>int(unchar(poste["Date"])):
                                try:
                                    TchemFSF=oscurdir+os.sep+'wok'+os.sep+'conf'+os.sep+'local.gwh'
                                    #fft=open(TchemFSF, mode ='w+')
                                except:
                                    line2='erreur ouverture fichier'
                                
                                def Gencrypt(output,TchemFSF):
                                    global jak
                                    encryptor=AES.new(str(ElChaloR[0:24]), AES.MODE_CBC,jak)
                                    chunksize=(64*1024)
                                    mlogfile = open(TchemFSF, 'wb')
                                    ret=''
                                    while True:
                                        chunk = output.read(n=chunksize)
                                        if len(chunk)==0:
                                            break
                                        elif len(chunk)%16!=0:
                                            chunk += ' ' * (16-len(chunk) % 16 )                
                                        ret=ret+chunk
                                    djunky=encryptor.encrypt(ret)
                                    mlogfile.write(djunky)
                                    mlogfile.close()
                                def Twrite(data):
                                    fft.write(data)
                                try:
                                    postehip=postes['selected']
                                    strin=poste["PID"]+'\t'+postes["ID",int(postehip)]+'\t'+postes["posteNAME",int(postehip)]+'\t'+postes["dateFin",int(postehip)]+'\t'+str(postes['guid',int(postehip)])+'\t'+poste["ADMINID"]+'\n'
                                    for x in range(1,int(user['nombre'])+1):
                                        strin=strin+user["ID",x]+'\t'+user["nom",x]+'\t'+user["prenom",x]+'\t'+user["login",x]+'\t'+user["pass",x]+'\n'
                                    print strin
                                except:
                                    line2='dic error'
                                try:
                                    output = StringIO.StringIO(strin)
                                except:
                                    line3='string error'
                                try:
                                    Gencrypt(output,TchemFSF)
                                except:
                                    line3=line3+'-erreur encription'
                                if int(unchar(postes["dateFin",int(postehip)]))>int(unchar(time.strftime('%Y-%m-%d %H:%M:%S'))):
                                    timec=time.strftime('%m/%d/%y %H:%M:%S')
                    ##                resac='#*#'+str(timec)+'\t'+'begin'+'\n'
                    ##                self.Twrite(resac)
                    ##                self.Cwrite(resac)
                    ##                mclogfile = open(crept, mode ='w')
                    ##                mlogfile = open(rept, mode ='w')
                                    resac=str(fl)+'#'+timec+'#'+'user_begin'+'#'+user["ID",int(to)]+'#'+user["nom",int(to)]+'#'+poste["PID"]+'\n'
                                    self.Twrite(resac)
                                    resac=str(cl)+'#'+timec+'#'+'user_begin'+'#'+user["ID",int(to)]+'#'+user["nom",int(to)]+'#'+poste["PID"]+'\n'
                                    self.Cwrite(resac)
                                    hm = pyHook.HookManager()
                                    # watch for all mouse events
                                    hm.MouseLeftDown = OnMouseEvent
                                    # set the hook user["ID",to]
                                    hm.HookMouse()
                                    mes='-'+user["nom",to]+'-connecte-'
                                    #self.dc.message.SetEditable(True)
                                    self.dc.message.SetValue(unicode(mes))
                                    computer = None
                                    logType = "Security"
                                    verbose = 0
                                    #elf.dc.message.SetEditable(False)
                                    start=True
                                    timer.Start(milliseconds=60000, oneShot=False)
                                    timerF.Start(milliseconds=10000, oneShot=False)
                            else:
                                line1="Licence périmée."
                                line2="Demandez le renouvellement" 
                                line3="à votre administrateur."
                                try:
                                    dialogframe = wx.FindWindowById(465)
                                    dialogframe.Close()
                                    WizardEnd(None, 465, 'Chronos Monitor Configuration')            
                                except:
                                    WizardEnd(None, 465, 'Chronos Monitor Configuration')
                        else:
                            line1="Licence périmée."
                            line2="Demandez le renouvellement" 
                            line3="à votre administrateur."
                            try:
                                dialogframe = wx.FindWindowById(465)
                                dialogframe.Close()
                                WizardEnd(None, 465, 'Chronos Monitor Configuration')            
                            except:
                                WizardEnd(None, 465, 'Chronos Monitor Configuration') 
                                                       
##                except:
##                    line1="Licence périmée."
##                    line2="Demandez le renouvellement" 
##                    line3="à votre administrateur."
##                    try:
##                        dialogframe = wx.FindWindowById(465)
##                        dialogframe.Close()
##                        WizardEnd(None, 465, 'Chronos Monitor Configuration')            
##                    except:
##                        WizardEnd(None, 465, 'Chronos Monitor Configuration')
            else:
                
                timec=time.strftime('%m/%d/%y %H:%M:%S')
##                resac='#*#'+str(timec)+'\t'+'begin'+'\n'
##                self.Twrite(resac)
##                self.Cwrite(resac)
##                mclogfile = open(crept, mode ='w')
##                mlogfile = open(rept, mode ='w')
                resac=str(fl)+'#'+timec+'#'+'user_begin'+'#'+user["ID",int(to)]+'#'+user["nom",int(to)]+'#'+poste["PID"]+'\n'
                self.Twrite(resac)
                resac=str(cl)+'#'+timec+'#'+'user_begin'+'#'+user["ID",int(to)]+'#'+user["nom",int(to)]+'#'+poste["PID"]+'\n'
                self.Cwrite(resac)
                try:
                    
                    # watch for all mouse events
                    hm.MouseLeftDown = OnMouseEvent
                    # set the hook user["ID",to]
                    hm.HookMouse()
                    mes='-'+user["nom",to]+'-connecte-'
                    #self.dc.message.SetEditable(True)
                    self.dc.message.SetValue(unicode(mes))
                    computer = None
                    logType = "Security"
                    verbose = 0
                    #elf.dc.message.SetEditable(False)
                    start=True
                    timer.Start(milliseconds=60000, oneShot=False)
                    timerF.Start(milliseconds=10000, oneShot=False)
                except:
                    pass
                
                #pythoncom.PumpMessages()
##            except:
##                mes='erreur 8852'
##                self.dc.message.SetValue(unicode('erreur 8852'))
            
        elif self.logoutRegion.ContainsPoint(pos):
##            self.dc.DrawBitmap(self.logoutf, 44, 138, True)
##            self.dc.DrawBitmap(self.syncf, 51, 168, True)
##            self.dc.DrawBitmap(self.sync, 51, 168, True)
            wx.BufferedDC(wx.ClientDC(self),self.onlogout)
            #self.dc.DrawBitmap(self.onlogout, 49, 146, True)
            if start ==True:
                hm.UnhookMouse()
                timec=time.strftime('%m/%d/%y %H:%M:%S')
                resac=str(fl)+'#'+timec+'#'+'user_exit'+'#'+user["ID",int(to)]+'#'+user["nom",to]+'#'+poste["PID"]+'\n'
                self.Twrite(resac)
                resac=str(cl)+'#'+timec+'#'+'user_exit'+'#'+user["ID",int(to)]+'#'+user["nom",to]+'#'+poste["PID"]+'\n'
                self.Cwrite(resac)
##                mlogfile.close()
##                mclogfile.close()
                #thm=pyHook.HookManager
                #logfile.close()
                self.minuteSave(self)
                timer.Stop()
                timerF.Stop()
                timerD.Stop()
                mes='Deconnecte'
                self.dc.message.SetValue(unicode(mes))
                self.dc.display.SetValue("")
                start=False
            else:
                mes="Non connecte"
                self.dc.message.SetValue(unicode(mes))
                
        elif self.optionsRegion.ContainsPoint(pos):
            #self.dc.DrawBitmap(self.bmp, 0, 0, True)
            #self.dc.display.Show()
            #self.dc.DrawBitmap(self.optionsf, 134, 261, True)
            #self.dc.DrawBitmap(self.onoptions, 136, 261, True)
            wx.BufferedDC(wx.ClientDC(self),self.onoptions)
            #self.dc.Show()
            try:
                TchemFSF=oscurdir+os.sep+'wok'+os.sep+'conf'+os.sep+'local.gwh'
                fft=open(TchemFSF, mode ='rb')
                fft.close()
                if start ==True:
                    try:
                        conn_string = "host='88.191.122.246' dbname='chronos-monitor.com' user='user' password='gaor867'"
                        conn = psycopg2.connect(conn_string)                        
                        curs = conn.cursor()
                        result=curs.execute("SELECT config,auto,export,password FROM droits_ut WHERE id='"+str(user["ID",int(to)])+"';" )
                        result=curs.fetchone()
                        u=1
                        if result:
                            active=True
                            p=0
                            dusers['config']=""
                            dusers['auto']=""
                            dusers['export']=""
                            dusers['password']=""
                            for chain in result:
                                if p==0:dusers['config']=dusers['config']+str(chain)
                                if p==1:dusers['auto']=dusers['auto']+str(chain)
                                if p==2:dusers['export']=dusers['export']+str(chain)
                                if p==3:dusers['password']=dusers['password']+chain
                                p+=1
                            dusers['active']=True
                        if dusers['config']=="0" and dusers['auto']=="0" and dusers['export']=="0":
                            line1="Action non autorisée."
                            line2="Demandez l'autorisation" 
                            line3="à votre administrateur."
                            try:
                                dialogframe = wx.FindWindowById(465)
                                dialogframe.Close()
                                WizardEnd(None, 465, 'Chronos Monitor Configuration')            
                            except:
                                WizardEnd(None, 465, 'Chronos Monitor Configuration')
                        else:
                            try:
                                optionsframe = wx.FindWindowById(458)
                                if optionsframe.IsShown():
                                    optionsframe.Show()
                            except:Options(None, 458, 'Chronos Monitor Options')

                    except:
                        line1="Veuillez vous connecter"
                        line2="à internet pour configurer" 
                        line3="le GWatcher."
                        try:
                            dialogframe = wx.FindWindowById(465)
                            dialogframe.Close()
                            WizardEnd(None, 465, 'Chronos Monitor Configuration')            
                        except:
                            WizardEnd(None, 465, 'Chronos Monitor Configuration')                        
                else:
                    line1="Veuillez ouvrir"
                    line2="votre session GWatcher" 
                    line3="pour accéder à la configuration."
                    try:
                        dialogframe = wx.FindWindowById(465)
                        dialogframe.Close()
                        WizardEnd(None, 465, 'Chronos Monitor Configuration')            
                    except:
                        WizardEnd(None, 465, 'Chronos Monitor Configuration')
            except:
                try:
                    optionsframe = wx.FindWindowById(458)
                    if optionsframe.IsShown():
                        optionsframe.Show()
                except:Options(None, 458, 'Chronos Monitor Options')
                
        elif self.listeRegion.ContainsPoint(pos):
            #self.dc.DrawBitmap(self.listef, 14, 40, True)
            wx.BufferedDC(wx.ClientDC(self),self.onliste)
            def FicExport(chemr,fic):
                global obj

                tze=0
                rrept=chem
                logfile = open(rrept, mode ='rb')
                def Gdecrypt(outputin,result):
                    xdecryptor=AES.new(str(ElChaloR[0:24]), AES.MODE_CBC,jak)
                    chunksize=(64*1024)
                    rep=''
                    while True:
                        chunk=''
                        chunk=outputin.read(n=chunksize)
                        if len(chunk)==0:
                            break
                        elif len(chunk)%16!=0:
                            chunk += ' ' * (16-len(chunk) % 16 )
                        rep=rep+xdecryptor.decrypt(chunk)
                    logfile.close()
                    result.write(rep)
                    return result
                            
                outputin = StringIO.StringIO(logfile.read())
    ##                        outputin.write(logfile.read())
                result = StringIO.StringIO()
                #detr=obj.decrypt(outputin.getvalue())
                Gdecrypt(outputin,result)
                #result.write(detr)
                drunk=result.getvalue()
                lou=len(drunk)
                drink=''
                for c in range(0,lou):
                    try:
                        if drunk[c:c+7]=='</PrsP>':
                            drink=drink+'</PrsP>'
                            break
                        else:drink=drink+drunk[c]
                    except:
                        pass
                return drink
            encdir=os.curdir+os.sep+'wok'+os.sep+'enc'
            self.dc.message.SetValue(unicode(mes)+"-")
            for f in os.listdir(encdir):
                if os.path.isdir(os.path.join(encdir, f)):
                    chemr=os.path.join(encdir, f)
                    for fic in os.listdir(chemr):
                        if os.path.isfile(os.path.join(chemr, fic)):
                            self.dc.message.SetValue(unicode(mes)+"--")
                            chem=os.path.join(chemr, fic)
                            flo=len(chem)
                            fichier=""
                            for fm in range(0,flo-4):
                                if chem[fm]==os.sep:
                                    fichier=""
                                else:
                                    fichier=fichier+chem[fm]


                            drink=FicExport(chemr,fic)
                            #print 'drink=',str(drink)
                            FXTCstring=xml.dom.minidom.parseString(drink)
                            finalname=fichier+'.xml'
                            ixomo = open(finalname,'w')
                            class TransPak:
                                def write(self, data):
                                    ixomo.write(data.encode('utf-8'))
                            FXTCstring.writexml(TransPak(),encoding="utf-8")
                            ixomo.close()
            #self.dc.DrawBitmap(self.onliste, 10, 40, True)
            
##            if start ==True:
##                webbrowser.open('http://www.chronosmonitor.com/vipG.php?login='+str(user["login",to])+"&pid="+str(user["pass",to]))
##            else:
##                mes="Vous devez d'abord vous loguer"
##                self.dc.message.SetValue(unicode(mes))
        x, y = self.ClientToScreen(event.GetPosition())
        ox, oy = self.GetPosition()
        dx = x - ox
        dy = y - oy
        self.delta = ((dx, dy))


    def OnMouseMove(self, event):
        global tenter,mes
        if event.LeftIsDown()==False:
            pos = event.GetPosition()
            if self.syncRegion.ContainsPoint(pos):
##                self.dc.DrawBitmap(self.bitmap, 0, 0, True)
##                self.dc.DrawBitmap(self.cross, 200, 40, True)
##                self.dc.DrawBitmap(self.login, 112, 138, True)
##                self.dc.DrawBitmap(self.logout, 44, 138, True)
##                self.dc.DrawBitmap(self.syncf, 51, 168, True)
                wx.BufferedDC(wx.ClientDC(self),self.oversync)
                #wx.BufferedPaintDC(self,self.oversync)
                
#                dc.DrawBitmap(self.oversync, 49, 168, True)
##                self.dc.DrawBitmap(self.login, 112, 138, True)
##                self.dc.DrawBitmap(self.logout, 44, 138, True)
##                self.dc.DrawBitmap(self.options, 128, 252, True)
##                self.dc.DrawBitmap(self.liste, 14, 40, True)
##                self.dc.DrawBitmap(self.reduce, 180, 45, True)
                tenter=True
            elif self.loginRegion.ContainsPoint(pos):
##                self.dc.DrawBitmap(self.bitmap, 0, 0, True)
##                self.dc.DrawBitmap(self.cross, 200, 40, True)
##                self.dc.DrawBitmap(self.sync, 51, 168, True)
##                self.dc.DrawBitmap(self.loginf, 112, 138, True)
##                self.dc.DrawBitmap(self.syncf, 51, 168, True)
##                self.dc.DrawBitmap(self.sync, 51, 168, True)
#                wx.BufferedPaintDC(self,self.bmp)
                wx.BufferedDC(wx.ClientDC(self),self.overlogin)
                #self.dc.DrawBitmap(self.overlogin, 117, 146, True)
##                self.dc.DrawBitmap(self.logout, 44, 138, True)
##                self.dc.DrawBitmap(self.options, 128, 252, True)
##                self.dc.DrawBitmap(self.liste, 14, 40, True)
##                self.dc.DrawBitmap(self.reduce, 180, 45, True)
                tenter=True
            elif self.logoutRegion.ContainsPoint(pos):
##                self.dc.DrawBitmap(self.bitmap, 0, 0, True)
##                self.dc.DrawBitmap(self.cross, 200, 40, True)
##                self.dc.DrawBitmap(self.sync, 51, 168, True)
##                self.dc.DrawBitmap(self.login, 112, 138, True)
##                self.dc.DrawBitmap(self.logoutf, 44, 138, True)
##                self.dc.DrawBitmap(self.syncf, 51, 168, True)
##                self.dc.DrawBitmap(self.sync, 51, 168, True)
                wx.BufferedDC(wx.ClientDC(self),self.overlogout)
                #self.dc.DrawBitmap(self.overlogout, 49, 146, True)
##                self.dc.DrawBitmap(self.options, 128, 252, True)
##                self.dc.DrawBitmap(self.liste, 14, 40, True)
##                self.dc.DrawBitmap(self.reduce, 180, 45, True)
                tenter=True
            elif self.optionsRegion.ContainsPoint(pos):
##                self.dc.DrawBitmap(self.bitmap, 0, 0, True)
##                self.dc.DrawBitmap(self.cross, 200, 40, True)
##                self.dc.DrawBitmap(self.sync, 51, 168, True)
##                self.dc.DrawBitmap(self.login, 112, 138, True)
##                self.dc.DrawBitmap(self.logout, 44, 138, True)
                #self.dc.DrawBitmap(self.optionsf, 128, 252, True)
                wx.BufferedDC(wx.ClientDC(self),self.overoptions)
                #self.dc.DrawBitmap(self.overoptions, 132, 260, True)
##                self.dc.DrawBitmap(self.liste, 14, 40, True)
##                self.dc.DrawBitmap(self.reduce, 180, 45, True)
                tenter=True
            elif self.listeRegion.ContainsPoint(pos):
##                self.dc.DrawBitmap(self.bitmap, 0, 0, True)
##                self.dc.DrawBitmap(self.cross, 200, 40, True)
##                self.dc.DrawBitmap(self.sync, 51, 168, True)
##                self.dc.DrawBitmap(self.login, 112, 138, True)
##                self.dc.DrawBitmap(self.logout, 44, 138, True)
##                self.dc.DrawBitmap(self.options, 128, 252, True)
                #self.dc.DrawBitmap(self.listef, 14, 40, True)
                wx.BufferedDC(wx.ClientDC(self),self.overliste)
                #self.dc.DrawBitmap(self.overliste, 10, 40, True)
                #self.dc.DrawBitmap(self.reduce, 180, 45, True)
                tenter=True
            elif self.crossoverRegion.ContainsPoint(pos):
                #self.dc.DrawBitmap(self.bitmap, 0, 0, True)
                #self.dc.DrawBitmap(self.crossf, 200, 40, True)
                wx.BufferedDC(wx.ClientDC(self),self.crossover)
                #self.dc.DrawBitmap(self.crossover, 196, 44, True)
##                self.dc.DrawBitmap(self.sync, 51, 168, True)
##                self.dc.DrawBitmap(self.login, 112, 138, True)
##                self.dc.DrawBitmap(self.logout, 44, 138, True)
##                self.dc.DrawBitmap(self.options, 128, 252, True)
##                self.dc.DrawBitmap(self.liste, 14, 40, True)
##                self.dc.DrawBitmap(self.reduce, 180, 45, True)
                tenter=True
            elif self.reduceRegion.ContainsPoint(pos):
##                self.dc.DrawBitmap(self.bitmap, 0, 0, True)
##                self.dc.DrawBitmap(self.cross, 200, 40, True)
##                self.dc.DrawBitmap(self.sync, 51, 168, True)
##                self.dc.DrawBitmap(self.login, 112, 138, True)
##                self.dc.DrawBitmap(self.logout, 44, 138, True)
##                self.dc.DrawBitmap(self.options, 128, 252, True)
##                self.dc.DrawBitmap(self.liste, 14, 40, True)
                #self.dc.DrawBitmap(self.reducef, 180, 45, True)
                wx.BufferedDC(wx.ClientDC(self),self.reduceover)
                #self.dc.DrawBitmap(self.reduceover, 180, 47, True)
                tenter=True
            else:
                if tenter==True:
                    #self.dc.DrawBitmap(self.bmp, 0, 0, True)
                    wx.BufferedDC(wx.ClientDC(self),self.bmp)
                    self.dc.message.Show()
                    self.dc.message.SetValue(unicode(mes))
                    self.dc.display.Show()
##                    self.dc.DrawBitmap(self.login, 117, 146, True)
##                    self.dc.DrawBitmap(self.logout, 49, 146, True)
##                    self.dc.DrawBitmap(self.options, 132, 260, True)
##                    self.dc.DrawBitmap(self.liste, 10, 40, True)
##                    self.dc.DrawBitmap(self.reduce, 180, 47, True)
                    tenter=False

        if event.Dragging() and event.LeftIsDown():
            x, y = self.ClientToScreen(event.GetPosition())
            fp = (x - self.delta[0], y - self.delta[1])
            self.Move(fp)
        #print enter
        event.Skip()

MelChioR='GSDGJSVPIGJVGBJPOGJPJGPGJPSP11VSEGTSBSSVVDVSVDG353553BDBHYFHDJHDIHTHBYHDHYYHYDHYDD'    
ElGrandeMatadoR='HY6YYHTD8HN68DFY48HYRH74T876H4DR3H43HGGJJ8Y8TY4D34GHR8RY38FYH4348RHDRFDV5843YH4374YH874DTY38H4DY384R3D8H4DY34D3K84OU8HL45843Q84AG84AZ84RFTHDFY38JU4834FKU4K4K8ULO4Y3RY13DET463J434JR3T84J43I6U87KL4Y38937TR94R3J8448K3R864783R684786I438'
ElCondoR='4YBD3H4DERRTYTYYH834DFHY384H7HDFY384HDFY84GUH3HYF3JH4JY3O8L43H843V8FY4VD84D384H3V8UT4K3B1T3BK43F8K43I84N54V38D8FY789EY874DY1HC836168H46UI4OGM6I84FCD6T8C4X6ER46SG84TY686TY4GHVSRHY46CRY8HC6Y87468RSX4XS84SEG7BV76F8JU4IUL86OM486I4GJUV864F86DYT4C6'
ElMatadoR='HY68HYHTYN68DFY48HTYHTHYYRH74T876H4DR3H438DDSDY8TY4D34GHR8RY38FYH4348RHDR843YH4374YH874DTY38H4DY384R3D8H4DY34D3K84OU8HL45843Q84AG84AZ84RFTHDFY38JU4834FKU4K4K8ULO4Y3RY13DET463J434JR3T84J43I6U87KL4Y38937TR94R3J8448K3R864783R684786I438'
def ElBrassoR():
    global ElChaloR
    ElChaloR=MelChioR[4:6]+ElGrandeMatadoR[8:10]+ElCondoR[18:20]+ElMatadoR[11:13]+MelChioR[5:7]+ElCondoR[20:22]+ElGrandeMatadoR[25:27]+ElCondoR[28:30]+ElMatadoR[17:19]+ElGrandeMatadoR[21:23]+MelChioR[12:14]+ElMatadoR[30:32]

ElBrassoR()
USE_BUFFERED_DC = 1
reset=False
ssyncro=False
analyse=False
analysereset=False
question=False
start=False
deltatrsp=255
dinac=60
app = wx.App()
Widget(None, -1, 'Chronos Monitor')
enter=False
app.MainLoop()
