#!/usr/bin/python2.7
# -*- coding: utf-8 -*-
##import wxversion
##wxversion.select('3.0')
import os
import wx
import wx.lib.scrolledpanel as scrolled
##wxversion.select('3.0')
#from wx import App
#import _winreg
#import MySQLdb
from Crypto.Cipher import AES
#from Crypto.Cipher import DES3
#try:

#    from io import StringIO
#except ImportError:
#    from cStringIO import StringIO
import StringIO
import time,sys,os,xml.dom.minidom,shutil, getopt
from time import localtime
##import pythoncom, pyHook
import types
import threading
import subprocess
##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
#import FSEvents
from fsevents import Observer, Stream
import fsevents
from Crypto.Hash import MD5
import codecs
import psycopg2
import webbrowser
#import psutil
from threading import Thread
import sys
from Foundation import NSObject, NSLog
from AppKit import NSApplication, NSApp, NSWorkspace
from Cocoa import *
import Cocoa
from Quartz import CGWindowListCopyWindowInfo, kCGWindowListOptionOnScreenOnly, kCGNullWindowID
from PyObjCTools import AppHelper
import threading
from threading import Thread
import wx.adv

class MyTaskBarIcon(wx.adv.TaskBarIcon):
    global line1,line2,line3,users,oscurdir
    def __init__(self, frame):
        global line1,line2,line3,users,oscurdir
        wx.adv.TaskBarIcon.__init__(self)
        self.frame = frame
        self.SetIcon(wx.Icon(oscurdir+os.sep+'img'+os.sep+'icone2.png', wx.BITMAP_TYPE_PNG), 'chronos monitor WIM')
        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)
        #print ('icon1')
 
    def CreatePopupMenu(self):
        menu = wx.Menu()
        #print ('icon2')
        menu.Append(1, 'Show')
        menu.Append(2, 'Hide')
        menu.Append(3, 'Close')
        menu.Append(4, 'Help')
        menu.Append(5, 'About')
        return menu

    def OnAbout(self,event):
        global line1,line2,line3
        line1="Chronos Monitor Work'in'Memories"
        line2="  version 2.08" 
        line3=str(users['serverdomain'])
        try:
            dialogframe = wx.FindWindowById(465)
            dialogframe.Close()
            WizardEnd(None, 465, 'Chronos Monitor Configuration')            
        except:
            WizardEnd(None, 465, 'Chronos Monitor Configuration')

    def OnHelp(self,event):
        global oscurdir
        path="file://"+oscurdir+"/doc/WIM-HeLP.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,476):
            try:
                frame=wx.FindWindowById(x)
                if frame.IsShown():
                    frame.Close()
            except:
                pass
        self.frame.Close()
        os._exit(0)

    def OnTaskBarActivate(self, event):
        if not self.frame.IsShown():
            self.frame.Show()
        for x in range(458,476):
            try:
                frame=wx.FindWindowById(x)
                if not frame.IsShown():
                    frame.Show()
            except:
                pass
##        try: # it's possible for this event to come when the frame is closed
##            self.GetTopWindow().Raise()
##        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,476):
            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,deltatrsp,oscurdir
    def __init__(self, parent, id, title):
        global line1,line2,line3,keyvalue,postes,users,deltatrsp,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(8, wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL, 
		wx.FONTWEIGHT_BOLD, False, 'ComicSansMS')

        self.hasShape=False
        self.delta=(0,0)
        self.image_file = oscurdir+os.sep+'img'+os.sep+'info-normal.gif'
        self.bmp = wx.Bitmap(self.image_file, wx.BITMAP_TYPE_GIF)
        
        self.bitmap = wx.Bitmap(oscurdir+os.sep+'img'+os.sep+'info-normal.png', wx.BITMAP_TYPE_PNG)
        self.wizard = wx.Bitmap(oscurdir+os.sep+'img'+os.sep+'info-normal.png', wx.BITMAP_TYPE_PNG)
        self.wizarda = wx.Bitmap(oscurdir+os.sep+'img'+os.sep+'info-appui.png', wx.BITMAP_TYPE_PNG)
        self.wizardr = wx.Bitmap(oscurdir+os.sep+'img'+os.sep+'info-rollover.png', wx.BITMAP_TYPE_PNG)
        self.close = wx.Bitmap(oscurdir+os.sep+'img'+os.sep+'close-normal.png', wx.BITMAP_TYPE_PNG)
        self.closer = wx.Bitmap(oscurdir+os.sep+'img'+os.sep+'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.SetTransparent(int(deltatrsp))
        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.Region(self.bitmap)
        self.wizardRegion = wx.Region(self.wizard)
        self.closeRegion = wx.Region(self.close)
        
        self.wizardRegion.Intersect(self.bitmapRegion)
        self.wizardRegion.Offset(60, 98)

        self.closeRegion.Intersect(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
        #self.OnDraw()

    def SetNoteShape(self, *event):
        region = wx.Region(self.bmp)
        self.hasShape=self.SetShape(region)

    def DShow(self):
        global line1,line2,line3
        self.wdc.DrawText(str(line1),10,40)
        self.wdc.DrawText(str(line2),10,55)
        self.wdc.DrawText(str(line3),10,70)

    def Draw(self):
        global line1,line2,line3
        self.wdc = wx.ClientDC(self)
        self.wdc.font1 = wx.Font(10, 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(str(line1),18,40)
        self.wdc.DrawText(str(line2),18,55)
        self.wdc.DrawText(str(line3),18,70)
        self.Show ( True )

    def OnPaint(self, event):
        global line1,line2,line3
        wx.BufferedPaintDC(self,self.bitmap)
        self.wdc = wx.ClientDC(self)
        self.wdc.font1 = wx.Font(10, 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(str(line1),18,40)
        self.wdc.DrawText(str(line2),18,55)
        self.wdc.DrawText(str(line3),18,70)
        #self.DShow()
        #self.Draw()
        event.Skip()



    def OnDraw(self):
        
        #self.Draw()
        self.DShow()



    def OnLeftDown(self, event):
        pos = event.GetPosition()
        if self.closeRegion.Contains(pos):
            self.Close()
        elif self.wizardRegion.Contains(pos):
            #wx.BufferedDC(wx.ClientDC(self),self.wizarda)
            if line1=="Licence is out-of-date.":
                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.Contains(pos):
                #wx.BufferedDC(wx.ClientDC(self),self.closer)
                self.DShow()
                enter=True
            elif self.wizardRegion.Contains(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)
        event.Skip()

class UnInstall(wx.Frame):
    global enter,line1,line2,line3,keyvalue,poste,users,deltatrsp,oscurdir
    def __init__(self, parent, id, title):
        global line1,line2,line3,keyvalue,poste,users,deltatrsp,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(8, wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL, 
		wx.FONTWEIGHT_BOLD, False, 'ComicSansMS')

        self.hasShape=False
        self.delta=(0,0)

        self.image_file = oscurdir+os.sep+'img'+os.sep+'info-normal.gif'
        self.bmp = wx.Bitmap(self.image_file, wx.BITMAP_TYPE_GIF)
        
        self.bitmap = wx.Bitmap(oscurdir+os.sep+'img'+os.sep+'question-normal.png', wx.BITMAP_TYPE_PNG)
        self.wizard = wx.Bitmap(oscurdir+os.sep+'img'+os.sep+'question-normal.png', wx.BITMAP_TYPE_PNG)
        self.close = wx.Bitmap(oscurdir+os.sep+'img'+os.sep+'close-normal.png', wx.BITMAP_TYPE_PNG)
        self.closer = wx.Bitmap(oscurdir+os.sep+'img'+os.sep+'question-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.SetTransparent(int(deltatrsp))
        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.Region(self.bitmap)
        self.wizardRegion = wx.Region(self.wizard)
        self.closeRegion = wx.Region(self.close)
        

        self.closeRegion.Intersect(self.bitmapRegion)
        self.closeRegion.Offset(192, 7)
##        self.dc = wx.ClientDC(self)
##        self.dc.DrawBitmap(self.bitmap, 0, 0, True)
##        #wx.BufferedDC(self.gwdc,self.bitmap)
##        self.dc.font1 = wx.Font(10, 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.DrawText("uninstall will descativate your workstation",15,30)
##        self.dc.DrawText("you will see the workstation again in wizard",15,45)
##        self.dc.DrawText("Really want to desactivate the workstation ?",15,60)
##        self.dc.oui = wx.Button ( self, -1, 'Yes',pos=(15,90) )
##        self.dc.oui.Bind(wx.EVT_BUTTON, self.desinstalle )
##        self.dc.non = wx.Button ( self, -1, 'No',pos=(110,90) )
##        self.dc.non.Bind(wx.EVT_BUTTON, self.annule )
        #self.wdc.oui.Show ( True )
        #self.wdc.non.Show ( True )
##        self.Show ( True )
        #self.dc = wx.ClientDC(self)
        #self.dc.DrawBitmap(self.bitmap, 0, 0, True)

        self.Show(True)
#        self.Fit()
        #self.Centre()
        enter=False
        self.OnDraw()

    def SetNoteShape(self, *event):
        region = wx.Region(self.bmp)
        self.hasShape=self.SetShape(region)

    def desinstalle(self,event):
        global poste,line1,line2,line3,users
        try:
            conn_string = "host='"+str(users['serverip'])+"' dbname='chronos-monitor.com' user='chronos' password='gortex855'"
            conn = psycopg2.connect(conn_string)
            curs = conn.cursor()               
            intostr="""UPDATE postes SET guid='', activated='0' WHERE id='"""+str(poste["PID"])+"""';"""
            result=curs.execute(intostr)
            conn.commit()
            curs.close()
            conn.close()
            path=os.curdir+os.sep+'wok'+os.sep+'conf'+os.sep+'local.gwh'
            os.remove(path)
            self.Close()
            line1="Work Station unplugged"
            line2=""
            line3=""
            WizardEnd(None, 469, 'Chronos Monitor')
        except:
            line1="Error during uninstall"
            line2=""
            line3=""
            WizardEnd(None, 469, 'Chronos Monitor')            

    def annule(self,event):
        try:
            frame=wx.FindWindowById(473)
            if frame.IsShown():
                frame.Close()
        except:
            pass
        #self.Close()


    def DShow(self):
        self.dc.DrawText("doing will desactivate this workstation",15,30)
        self.dc.DrawText("you will see it again in the wizard",15,45)
        self.dc.DrawText("Really want to desactivate workstation ?",15,60)


    def Draw(self):
        global line1,line2,line3,dc
        #self.dc = wx.ClientDC(self)
        #self.dc.DrawBitmap(self.bitmap, 0, 0, True)
        self.dc.font1 = wx.Font(10, 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.DrawText("doing will desactivate this workstation",15,30)
        self.dc.DrawText("you will see it again in the wizard",15,45)
        self.dc.DrawText("Really want to desactivate workstation ?",15,60)
        self.dc.oui = wx.Button ( self, -1, 'Yes',pos=(15,90) )
        self.dc.oui.Bind(wx.EVT_BUTTON, self.desinstalle )
        self.dc.non = wx.Button ( self, -1, 'No',pos=(110,90) )
        self.dc.non.Bind(wx.EVT_BUTTON, self.annule )
        #self.wdc.oui.Show ( True )
        #self.wdc.non.Show ( True )
        self.Show ( True )

    def OnPaint(self, event):
        wx.BufferedPaintDC(self,self.bitmap)
        #self.gwdc.DrawText("doing will desactivate this workstation",15,30)
        #self.gwdc.DrawText("you will see it again in the wizard",15,45)
        #self.gwdc.DrawText("Really want to desactivate workstation ?",15,60)
        #self.DShow()
        #self.Draw()
        self.dc = wx.ClientDC(self)
        self.dc.DrawBitmap(self.bitmap, 0, 0, True)
        self.dc.font1 = wx.Font(10, 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.DrawText("doing will desactivate this workstation",15,30)
        self.dc.DrawText("you will see it again in the wizard",15,45)
        self.dc.DrawText("Really want to desactivate workstation ?",15,60)
        self.dc.oui = wx.Button ( self, -1, 'Yes',pos=(15,90) )
        self.dc.oui.Bind(wx.EVT_BUTTON, self.desinstalle )
        self.dc.non = wx.Button ( self, -1, 'No',pos=(110,90) )
        self.dc.non.Bind(wx.EVT_BUTTON, self.annule )
        event.Skip()




    def OnDraw(self):
        #self.Draw()
        self.DShow()



    def OnLeftDown(self, event):
        pos = event.GetPosition()
        if self.closeRegion.Contains(pos):
            self.Close()
##        elif self.wizardRegion.Contains(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))
        event.Skip()

    def OnMouseMove(self, event):
        global enter
        if event.LeftIsDown()==False:
            pos = event.GetPosition()
            if self.closeRegion.Contains(pos):
                #wx.BufferedDC(wx.ClientDC(self),self.closer)
                #self.Draw()
                enter=True
##            elif self.wizardRegion.Contains(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,oscurdir,enter,line1,line2,line3,keyvalue,postes,users,box,ElChaloR,posteid,deltatrsp,dc
    def __init__(self, parent, id, title,HOST_IP,HOST_DOMAIN):
        global jak,oscurdir,line1,line2,line3,keyvalue,postes,users,box,ElChaloR,oscurdir,posteid,dc
        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, 'ComicSansMS')

        #self.panel=wx.Panel(self,-1), size=(250, 600)

        self.hasShape=False
        self.delta=(0,0)
        self.HOST_IP=HOST_IP
        self.HOST_DOMAIN=HOST_DOMAIN
        self.image_file = oscurdir+os.sep+'img'+os.sep+'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(oscurdir+os.sep+'img'+os.sep+'wizard_appui.png', wx.BITMAP_TYPE_PNG)
        self.wizard = wx.Bitmap(oscurdir+os.sep+'img'+os.sep+'valider-normal.png', wx.BITMAP_TYPE_PNG)
        #self.wizardf = wx.Bitmap(oscurdir+os.sep+'img'+os.sep+'validerf.png', wx.BITMAP_TYPE_PNG)
        self.wizarda = wx.Bitmap(oscurdir+os.sep+'img'+os.sep+'wizard_appui.png', wx.BITMAP_TYPE_PNG)
        self.wizardr = wx.Bitmap(oscurdir+os.sep+'img'+os.sep+'wizard_rollover.png', wx.BITMAP_TYPE_PNG)
        self.close = wx.Bitmap(oscurdir+os.sep+'img'+os.sep+'close-normal.png', wx.BITMAP_TYPE_PNG)
 #       self.closef = wx.Bitmap(oscurdir+os.sep+'img'+os.sep+'close-fond2.png', wx.BITMAP_TYPE_PNG)
        self.closer = wx.Bitmap(oscurdir+os.sep+'img'+os.sep+'wizard_close.png', wx.BITMAP_TYPE_PNG)
        self.fond1 = wx.Bitmap(oscurdir+os.sep+'img'+os.sep+'wizard-fond.png', wx.BITMAP_TYPE_PNG)
        self.fond2 = wx.Bitmap(oscurdir+os.sep+'img'+os.sep+'wizard-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()))

        if wx.Platform == '__WXGTK__':
            self.Bind(wx.EVT_WINDOW_CREATE, self.SetNoteShape)
        else: self.SetNoteShape()

        enter=False         
        #MyButton(self.panel,-1,(47,168),oscurdir+os.sep+'img'+os.sep+'sync-normal.png',oscurdir+os.sep+'img'+os.sep+'sync-rollover.png',oscurdir+os.sep+'img'+os.sep+'appui-sync.png')
        #self.SetTransparent(220)
        self.SetTransparent(int(deltatrsp))

        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.Region(self.bitmap)
        self.wizardRegion = wx.Region(self.wizard)
        self.closeRegion = wx.Region(self.close)


        self.wizardRegion.Intersect(self.bitmapRegion)
        self.wizardRegion.Offset(58, 520)

        self.closeRegion.Intersect(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 = wx.ClientDC(self)
        self.dc.DrawBitmap(self.bitmap, 0, 0, True)
        #dc = wx.BufferedDC(dcb)
##        #self.nkey=wx.TextCtrl(self,wx.ID_ANY,'',pos=(20,39),size=(180,20))
        

#        key=""
        
#        self.Fit()
        self.Show(True)
        self.Centre()
        self.OnDraw()
##    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.RegionColour(self.bitmap,'#000000',0)
        region = wx.Region(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,postes
        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)
        postes['selected']=postehip
        #print posteid
        
    def OnCheck(self,event):
        global uzerid,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):
        #global dc
        self.dc.DrawText("Choose your workstation:",10,30)
        self.dc.DrawText("Choose users of workstation:",10,280)
        #pass

    def Draw(self):
        global postes,users,box,posteid,postehip
        #self.dc = wx.Frame()
        #self.dc = wx.ClientDC(self)
        #self.dc.DrawBitmap(self.bitmap, 0, 0, True)
        #self.dc.SetFont(self.font)
        #self.dc.SetTextForeground('BLACK')
#        self.dc.DrawBitmap(self.wizarda, 0, 0, True)
##        self.self.dc.DrawBitmap(self.close, 200, 12, True)
        #self.dc.DrawBitmap(self.wizard, 60, 520, True)
        self.dc.font1 = wx.Font(10, wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_NORMAL, False)
#        self.dc.SetTextBackground(wx.NullColour)
        self.dc.SetTextForeground('BLACK')
        self.dc.SetFont(self.dc.font1)
        #self.self.dc.SetTextSize(8)
        self.dc.DrawText("Choose your workstation:",10,30)
#        self.self.dc.panel=WizardPanelPostes(self.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.panel.SetAutoLayout(1)
        #self.dc.panel.SetupScrolling()
        self.dc.postbox.FitInside(self.dc.panel)
#        self.dc.panel.Layout()
        #self.dc.postbox.FitInside(self.dc.panel)
        #self.dc.SetSizerAndFit(self.dc.panel)
        #self.dc.postbox.Bind(wx.EVT_ERASE_BACKGROUND, self.OnEraseBackground1)
        self.dc.DrawText("Choose users of workstation:",10,280)
        self.dc.panel2=scrolled.ScrolledPanel(self,-1,(10,300),(200,200), style=wx.SUNKEN_BORDER)
        self.dc.panel2.SetupScrolling(scroll_x=True,scroll_y=True)
        #self.dc.panel2.SetBackgroundColour('#EAEAE9')
        self.dc.DrawBitmap(self.fond2, 10, 300, True)
        #self.dc.panel=MyScrollPanel(self.dc)
        self.dc.postbox2=wx.BoxSizer(wx.VERTICAL)
        self.dc.box={}
        #print 'user'+str(users['nom',1])+' '+str(users['prenom',1])
        for x in range(1,int(users['nombre'])+1):
            #print x
            posy=(int(x)*10)
            idx=3000+int(x)
            self.dc.box[x]=wx.CheckBox(self.dc.panel2,idx,label=str(users['nom',int(x)])+' '+str(users['prenom',int(x)]))
            self.dc.postbox2.Add(self.dc.box[x],wx.LEFT)
            self.dc.box[x].Bind(wx.EVT_CHECKBOX, self.OnCheck)
            #print 'box'+str(users['nom',int(x)])
        self.dc.panel2.SetSizer(self.dc.postbox2)
#        self.dc.panel2.SetAutoLayout(1)
#        self.dc.DrawBitmap(self.wizarda, 0, 0, True)
##        self.dc.button = wx.Button(self,label="Go",pos=(80,550), size=(50,50))
##        self.dc.button.Bind(wx.EVT_BUTTON, self.Go)
        #self.dc.panel2.SetupScrolling()
#        self.dc.postbox2.FitInside(self.dc.panel2)
#        self.dc.panel2.Layout()
        self.dc.postbox2.FitInside(self.dc.panel2)
        #self.SetSizerAndFit(self.dc.panel2)
#        self.dc.Fit()
#        self.Centre()
#        self.Show(True)
#        event.Skip()
#        self.Layout()

    def OnPaint(self, event):
        global postes,users,box,posteid,postehip,dc
        #wx.BufferedDC(self.dc,self.bitmap)
        #wx.BufferedPaintDC(self,self.bitmap)
        wx.BufferedPaintDC(self,self.bitmap)
##        dc = wx.PaintDC(self)
##        self.dc.DrawBitmap(self.bitmap, 0, 0, True)
##        #self.dc.SetFont(self.font)
##        #self.dc.SetTextForeground('BLACK')
###        self.dc.DrawBitmap(self.wizarda, 0, 0, True)
####        self.self.dc.DrawBitmap(self.close, 200, 12, True)
##        #self.dc.DrawBitmap(self.wizard, 60, 520, True)
##        self.dc.font1 = wx.Font(10, wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_NORMAL, False)
##        self.dc.SetTextBackground(wx.NullColour)
##        self.dc.SetTextForeground('BLACK')
##        self.dc.SetFont(self.dc.font1)
##        #self.self.dc.SetTextSize(8)
##        self.dc.DrawText("Choose your workstation:",10,30)
###        self.self.dc.panel=WizardPanelPostes(self.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.panel.SetAutoLayout(1)
##        #self.dc.panel.SetupScrolling()
##        #self.dc.postbox.FitInside(self.dc.panel)
###        self.dc.panel.Layout()
##        #self.dc.postbox.FitInside(self.dc.panel)
##        #self.dc.SetSizerAndFit(self.dc.panel)
##        #self.dc.postbox.Bind(wx.EVT_ERASE_BACKGROUND, self.OnEraseBackground1)
##        self.dc.DrawText("Choose users of workstation:",10,280)
##        self.dc.panel2=scrolled.ScrolledPanel(self,-1,(10,300),(200,200), style=wx.SUNKEN_BORDER)
##        self.dc.panel2.SetupScrolling(scroll_x=True,scroll_y=True)
##        #self.dc.panel2.SetBackgroundColour('#EAEAE9')
##        #self.dc.DrawBitmap(self.fond2, 10, 300, True)
##        #self.dc.panel=MyScrollPanel(self.dc)
##        self.dc.postbox2=wx.BoxSizer(wx.VERTICAL)
##        self.dc.box={}
##        #print 'user'+str(users['nom',1])+' '+str(users['prenom',1])
##        for x in range(1,int(users['nombre'])+1):
##            #print x
##            posy=(int(x)*10)
##            idx=3000+int(x)
##            self.dc.box[x]=wx.CheckBox(self.dc.panel2,idx,label=str(users['nom',int(x)])+' '+str(users['prenom',int(x)]))
##            self.dc.postbox2.Add(self.dc.box[x],wx.LEFT)
##            self.dc.box[x].Bind(wx.EVT_CHECKBOX, self.OnCheck)
##            #print 'box'+str(users['nom',int(x)])
##        self.dc.panel2.SetSizer(self.dc.postbox2)
##        self.dc.panel2.SetAutoLayout(1)
##        self.dc.DrawBitmap(self.wizarda, 0, 0, True)
##        self.dc.button = wx.Button(self,label="Go",pos=(80,550), size=(50,50))
##        self.dc.button.Bind(wx.EVT_BUTTON, self.Go)
        #self.dc = wx.ClientDC(self)
        #wx.BufferedPaintDC(self,self.bitmap)
        #dc = wx.ClientDC(self)
        #dc.DrawBitmap(self.bitmap, 0, 0, True)
        #self.Draw()
#        self.Show(True)
        #self.bdc = wx.BufferedDC(seslf.cdc)
        #self.nkey=wx.TextCtrl(self,wx.ID_ANY,'',pos=(20,39),size=(180,20))
        #self.Show(True)
        #self.Fit()
        #self.Centre()
        #wx.BufferedPaintDC(self,self.bitmap)

#============================================================        
        #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),oscurdir+os.sep+'img'+os.sep+'sync-normal2.png',oscurdir+os.sep+'img'+os.sep+'sync-rollover2.png',oscurdir+os.sep+'img'+os.sep+'appui-sync2.png')
        event.Skip()



##
    def OnDraw(self):
#        wx.BufferedDC(self.dc,self.bitmap)
        self.Draw()
#        self.DShow()
        

    def Go(self,event):
        global jak,line1,line2,line3,keyvalue,posteid,ElChaloR,postehip,oscurdir,users
        line3=""
        if postes['selected']!=False:
            if postes["ID",int(postes['selected'])]!='':
                #print 'bingo1'
                conn_string = "host='"+str(self.HOST_IP)+"' dbname='chronos-monitor.com' user='chronos' password='gortex855'"
                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)
                    conn.commit()
                    #print 'bingo3'
                    

                intostr="""UPDATE postes SET guid='"""+str(keyvalue)+"""', activated='1' WHERE id='"""+str(posteid)+"""';"""
                        
                result=curs.execute(intostr)
                conn.commit()
                curs.close()
                conn.close()
        else:
                #print 'bingo2-'+str(posteid)
                conn_string = "host='"+str(self.HOST_IP)+"' dbname='chronos-monitor.com' user='chronos' password='gortex855'"
                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'
            #print ('-conffile-'+str(TchemFSF))
            #fft=open(TchemFSF, mode ='w+')
        except:
            line2='error opening file'
        try:
            pass
        except:
            line2='error opening 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:
        users["serverip"]=self.HOST_IP
            #print '1'
        users["serverdomain"]=self.HOST_DOMAIN
        strin='ip:'+str(self.HOST_IP)+'\t'+str(self.HOST_DOMAIN)+'\t'+str(postes["PID"])+'\t'+str(postes["ID",int(postes['selected'])])+'\t'+postes["posteNAME",int(postes['selected'])]+'\t'+str(postes["dateFin",int(postes['selected'])])+'\t'+str(postes["guid",int(postes['selected'])])+'\t'+str(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+'-encryption errot'
        try:
            line1="Your work station is now configured"
            line2=""
        except:
            line1="error during work station configuration"


        self.Close()
        try:
            dialogframe = wx.FindWindowById(465)
            dialogframe.Close()
            WizardEnd(None, 465, 'Chronos Monitor Configuration')            
        except:
            WizardEnd(None, 465, 'Chronos Monitor Configuration')   
        

    def OnLeftDown(self, event):
        global jak,line1,line2,line3,keyvalue,posteid,ElChaloR,postehip,oscurdir,users
        #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.Contains(pos):
            self.Close()
        elif self.wizardRegion.Contains(pos):
            line3=""
            if postes['selected']!=False:
                if postes["ID",int(postes['selected'])]!=posteid:
                    #print 'bingo1'
                    conn_string = "host='"+str(self.HOST_IP)+"' dbname='chronos-monitor.com' user='chronos' password='gortex855'"
                    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)
                        conn.commit()
                        #print 'bingo3'
                        

                    intostr="""UPDATE postes SET guid='"""+str(keyvalue)+"""', activated='1' WHERE id='"""+str(posteid)+"""';"""
                            
                    result=curs.execute(intostr)
                    conn.commit()
                    curs.close()
                    conn.close()
            else:
                    #print 'bingo2-'+str(posteid)
                    conn_string = "host='"+str(self.HOST_IP)+"' dbname='chronos-monitor.com' user='chronos' password='gortex855'"
                    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='error opening file'
            try:
                pass
            except:
                line2='error opening 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:
                users["serverip"]=self.HOST_IP
                #print '1'
                users["serverdomain"]=self.HOST_DOMAIN
                strin='ip:'+str(self.HOST_IP)+'\t'+str(self.HOST_DOMAIN)+'\t'+str(postes["PID"])+'\t'+str(postes["ID",int(postes['selected'])])+'\t'+postes["posteNAME",int(postes['selected'])]+'\t'+str(postes["dateFin",int(postes['selected'])])+'\t'+str(postes["guid",int(postes['selected'])])+'\t'+str(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+'-encryption errot'
            try:
                line1="Your work station is now configured"
                line2=""
            except:
                line1="error during work station configuration"


            self.Close()
            try:
                dialogframe = wx.FindWindowById(465)
                dialogframe.Close()
                WizardEnd(None, 465, 'Chronos Monitor Configuration')            
            except:
                WizardEnd(None, 465, 'Chronos Monitor Configuration')   
        x, y = self.ClientToScreen(event.GetPosition())
        ox, oy = self.GetPosition()
        dx = x - ox
        dy = y - oy
        self.delta = ((dx, dy))

        #event.Skip()


    def OnMouseMove(self, event):
        global enter,line1,line2,line3,dc
        pos = event.GetPosition()
        if self.closeRegion.Contains(pos):
            #wx.BufferedDC(wx.ClientDC(self),self.closer)
            #self.DShow()
            enter=True
        elif self.wizardRegion.Contains(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.Contains(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,deltatrsp,users,oscurdir
    def __init__(self, parent, id, title):
        global jak,line1,line2,line3,keyvalue,poste,user,dc,box,paned,ElChaloR,oscurdir,deltatrsp,users,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, 'ComicSansMS')

        #self.panel=wx.Panel(self,-1)

        self.hasShape=False
        self.delta=(0,0)

        self.image_file = oscurdir+os.sep+'img'+os.sep+'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(oscurdir+os.sep+'img'+os.sep+'wizard_appui.png', wx.BITMAP_TYPE_PNG)
        self.wizard = wx.Bitmap(oscurdir+os.sep+'img'+os.sep+'valider-normal.png', wx.BITMAP_TYPE_PNG)
        #self.wizardf = wx.Bitmap(oscurdir+os.sep+'img'+os.sep+'validerf.png', wx.BITMAP_TYPE_PNG)
        self.wizarda = wx.Bitmap(oscurdir+os.sep+'img'+os.sep+'wizard_appui.png', wx.BITMAP_TYPE_PNG)
        self.wizardr = wx.Bitmap(oscurdir+os.sep+'img'+os.sep+'wizard_rollover.png', wx.BITMAP_TYPE_PNG)
        self.close = wx.Bitmap(oscurdir+os.sep+'img'+os.sep+'close-normal.png', wx.BITMAP_TYPE_PNG)
 #       self.closef = wx.Bitmap(oscurdir+os.sep+'img'+os.sep+'close-fond2.png', wx.BITMAP_TYPE_PNG)
        self.closer = wx.Bitmap(oscurdir+os.sep+'img'+os.sep+'wizard_close.png', wx.BITMAP_TYPE_PNG)
        self.fond1 = wx.Bitmap(oscurdir+os.sep+'img'+os.sep+'wizard-fond.png', wx.BITMAP_TYPE_PNG)
        self.fond2 = wx.Bitmap(oscurdir+os.sep+'img'+os.sep+'wizard-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()))

        if wx.Platform == '__WXGTK__':
            self.Bind(wx.EVT_WINDOW_CREATE, self.SetNoteShape)
        else: self.SetNoteShape()

        enter=False         
        #MyButton(self.panel,-1,(47,168),oscurdir+os.sep+'img'+os.sep+'sync-normal.png',oscurdir+os.sep+'img'+os.sep+'sync-rollover.png',oscurdir+os.sep+'img'+os.sep+'appui-sync.png')
        #self.SetTransparent(220)
        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.Region(self.bitmap)
        self.wizardRegion = wx.Region(self.wizard)
        self.closeRegion = wx.Region(self.close)


        self.wizardRegion.Intersect(self.bitmapRegion)
        self.wizardRegion.Offset(58, 520)

        self.closeRegion.Intersect(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=""
        
        self.OnDraw()
##    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.RegionColour(self.bitmap,'#000000',0)
        region = wx.Region(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'
        isconfig=os.path.isfile(TchemFSF)
        if isconfig==True:
            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={}
            users={}
            l=0
            users['serverip']=""
            users['serverdomain']=""
            poste["PID"]=""
            poste["ID"]=""
            poste["posteNAME"]=""
            poste["Date"]=""
            poste["GUID"]=""
            poste["ADMINID"]=""
            T=False
            ip_enter=False
            go_on=True
            for char in lines:
                if char=='\t':
                    p+=1
                    ip_enter=False
                    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 and char in ['i','p',':']:
                    ip_enter=True
                    go_on=False
                    continue
                if go_on==False:
                    if ip_enter==True and p==0 and l==0:
                        users['serverip']=users['serverip']+char
                    if p==1 and l==0:users['serverdomain']+char
                    if p==2 and l==0:poste["PID"]=poste["PID"]+char
                    if p==3 and l==0:poste["ID"]=poste["ID"]+char
                    if p==4 and l==0:poste["posteNAME"]=poste["posteNAME"]+char
                    if p==5 and l==0:poste["Date"]=poste["Date"]+char
                    if p==6 and l==0:poste["GUID"]=poste["GUID"]+char
                    if p==7and 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
                else:
                    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
                    users['serverip']='62.210.195.95'
                    users['serverdomain']='http://www.chronosmonitor.com'                    
            user["nombre"]=l
            try:
                conn_string = "host='"+str(users['serverip'])+"' dbname='chronos-monitor.com' user='chronos' password='gortex855'"
                conn = psycopg2.connect(conn_string)
                curs = conn.cursor()
                result=curs.execute("SELECT nom,prenom,id,admin,login,pass,serverip,serverdomain FROM users WHERE idadmin='"+str(poste["ADMINID"])+"';" )
                result=curs.fetchall()
                u=1
                users['nombre']=u
                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]=""
                        users['pass',u]=""
                        users['serverip']=""
                        users['serverdomain']=""
                        users["Checked"]=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)
                            if p==6:users['serverip']=users['serverip']+str(char)
                            if p==7:users['serverdomain']=users['serverdomain']+str(char)
                            p+=1
                        users['nombre']=u
                        u+=1
            except:
                line1="Connection internet indisponible"
        else:
            line1="Configurez d'abord le poste"

    def OnApply(self,event):
        global posteid
        for x in range(1,int(user['nombre'])+1):
            pass
    def DShow(self):
        self.dc.DrawText("Please choose user's work station:",10,30)

    def Draw(self):
        global poste,users,dc,box,panelp
        #self.dc = wx.ClientDC(self)
        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("Please choose user's work station:",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.DShow()
        event.Skip()




    def OnDraw(self):
        self.ChargePoste()
        self.Draw()        



    def OnLeftDown(self, event):
        global jak,line1,line2,line3,keyvalue,dc,posteid,ElChaloR,posteid,postehip,oscurdir,poste,users
        pos = event.GetPosition()
        if self.closeRegion.Contains(pos):
            self.Close()
        elif self.wizardRegion.Contains(pos):
            line3=""
            try:
                TchemFSF=oscurdir+os.sep+'wok'+os.sep+'conf'+os.sep+'local.gwh'
            except:
                line2='error opening file 112'
            try:
                pass
            except:
                line2='error opening string 112'
##            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='ip:'+users["serverip"]+'\t'+users["serverdomain"]+'\t'+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 -118'
            try:
                Gencrypt(output,TchemFSF)
            except:
                line2='encryption error - 118'
            try:
                line1="User's now configured"
                line2=""
            except:
                line1="error during configuration registration"
                line2=""


            self.Close()
            try:
                dialogframe = wx.FindWindowById(465)
                dialogframe.Close()
                WizardEnd(None, 465, 'Chronos Monitor Configuration')            
            except:
                WizardEnd(None, 465, 'Chronos Monitor Configuration')
   
        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.Contains(pos):
            #wx.BufferedDC(wx.ClientDC(self),self.closer)
            #self.DShow()
            enter=True
        elif self.wizardRegion.Contains(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 WizardActivationTwo(wx.Frame):
    global enter,line1,line2,keyvalue,postes,users,key,deltatrsp,oscurdir
    def __init__(self, parent, id, title,HOST_IP):
        global line1,line2,keyvalue,postes,users,key,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, 'ComicSansMS')

        #self.panel=wx.Panel(self,-1)

        self.hasShape=False
        self.delta=(0,0)
        self.HOST_IP=HOST_IP
        self.image_file = oscurdir+os.sep+'img'+os.sep+'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(oscurdir+os.sep+'img'+os.sep+'code_0.png', wx.BITMAP_TYPE_PNG)
        self.wizard = wx.Bitmap(oscurdir+os.sep+'img'+os.sep+'valider-normal.png', wx.BITMAP_TYPE_PNG)
        #self.wizardf = wx.Bitmap(oscurdir+os.sep+'img'+os.sep+'validerf.png', wx.BITMAP_TYPE_PNG)
        self.wizarda = wx.Bitmap(oscurdir+os.sep+'img'+os.sep+'code_appui.png', wx.BITMAP_TYPE_PNG)
        self.wizardr = wx.Bitmap(oscurdir+os.sep+'img'+os.sep+'code_rollover.png', wx.BITMAP_TYPE_PNG)
        self.close = wx.Bitmap(oscurdir+os.sep+'img'+os.sep+'close-normal.png', wx.BITMAP_TYPE_PNG)
        self.closer = wx.Bitmap(oscurdir+os.sep+'img'+os.sep+'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="visit chronosmonitor.com"
        line2="to obtain an activation key"
        enter=False         
        #MyButton(self.panel,-1,(47,168),oscurdir+os.sep+'img'+os.sep+'sync-normal.png',oscurdir+os.sep+'img'+os.sep+'sync-rollover.png',oscurdir+os.sep+'img'+os.sep+'appui-sync.png')
        #self.SetTransparent(220)
        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.Region(self.bitmap)
        self.wizardRegion = wx.Region(self.wizard)
        self.closeRegion = wx.Region(self.close)
        

        self.wizardRegion.Intersect(self.bitmapRegion)
        self.wizardRegion.Offset(60, 100)

        self.closeRegion.Intersect(self.bitmapRegion)
        self.closeRegion.Offset(190, 12)
        keyvalue="mac osx"

##        try:      
##            regroot=_winreg.HKEY_LOCAL_MACHINE
##            hKey=_winreg.OpenKey(regroot,"SOFTWARE\Microsoft\Cryptography",0,_winreg.KEY_READ)
##            keyvalue, type=_winreg.QueryValueEx(hKey, "MachineGuid")
##        except:
##            keyvalue=""
##        #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=""
        self.OnDraw()

##    def OnClose(self, event):
##        self.tskic.Destroy()
##        self.Destroy()


    def SetNoteShape(self, *event):
        #region=wx.RegionColour(self.bitmap,'#000000',0)
        region = wx.Region(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 = wx.ClientDC(self)
        #wx.BufferedDC(wx.ClientDC(self),self.bitmap)
        self.dc.SetFont(self.font)
        self.dc.SetTextForeground('WHITE')
        #panel=
        #MyBG(self,-1)
        #panel = MyPanel(self, -1)
        #MyButton(self,-1,(49,168),oscurdir+os.sep+'img'+os.sep+'sync-normal2.png',oscurdir+os.sep+'img'+os.sep+'sync-rollover2.png',oscurdir+os.sep+'img'+os.sep+'appui-sync2.png')
        self.dc.font1 = wx.Font(10, wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_NORMAL, False)
        self.dc.SetTextBackground(wx.NullColour)
        self.dc.SetTextForeground('WHITE')
        self.dc.SetFont(self.dc.font1)
        #self.dc.SetTextSize(8)
        self.dc.DrawText("Please enter the activation code :",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,70)
        self.dc.DrawText(str(line2),10,90)
        self.Show()

    def DShow(self):
        global line1,line2,key
        self.dc.DrawText("Please enter the activation code :",10,16)
        #self.dc.nkey.SetValue(str(key))
        self.dc.DrawText(str(line1),10,68)
        self.dc.DrawText(str(line2),10,78)
        #pass
        
    def OnPaint(self, event):
        
        wx.BufferedPaintDC(self,self.bitmap)
        self.DShow()
        #self.Draw()
        #wx.BufferedPaintDC(self,self.bitmap)
        
        

##        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),oscurdir+os.sep+'img'+os.sep+'sync-normal2.png',oscurdir+os.sep+'img'+os.sep+'sync-rollover2.png',oscurdir+os.sep+'img'+os.sep+'appui-sync2.png')
        event.Skip()



    def OnDraw(self):
        self.Draw()
        self.DShow()
        




    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.Contains(pos):
            self.Close()
        elif self.wizardRegion.Contains(pos):
            #self.dc.DrawBitmap(self.wizardf, 22, 40, True)
            #self.dc.DrawBitmap(self.wizarda, 60, 60, True)
            active=False
            if str(key)=="":
                line1="Please enter the activation code"
                line2="you can find it on your Wim account"
            else :
                #try:
                if key:
                    conn_string = "host='"+str(self.HOST_IP)+"' dbname='chronos-monitor.com' user='chronos' password='gortex855'"
                    conn = psycopg2.connect(conn_string)
                    curs = conn.cursor()
                    result=curs.execute("SELECT nom,prenom,id,admin,login,pass,idadmin,serverip,serverdomain FROM users WHERE keycode='"+str(key)+"';" )
                    result=curs.fetchall()
                    u=1
                    postes={}
                    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['serverip',u]=""
                            users['serverdomain',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)
                                if p==7:users['serverip',u]=users['serverip',u]+str(char)
                                if p==8:users['serverdomain',u]=users['serverdomain',u]+str(char)
                                p+=1
                            #print "nombre=",users['nombre']
                            #if pid:postes['ADMINID']=str(pid)
                            u+=1
                        users['serverip']=self.HOST_IP
                        self.HOST_DOMAIN=users['serverdomain',u-1]
                    try:
                        u=1
                        #print 'pid='+repr(postes['ADMINID'])
                        query2="SELECT id,postename,datefin,activated,guid FROM postes WHERE userid='"+str(postes['ADMINID'])+"' AND actif='1';"
                        #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']
                            
                        try:
                            dialogframe = wx.FindWindowById(467)
                            dialogframe.Close()
                            WizardSelect(None, 467, 'Chronos Monitor',str(self.HOST_IP),str(self.HOST_DOMAIN))            
                            self.Close()        
                        except:
                            WizardSelect(None, 467, 'Chronos Monitor',str(self.HOST_IP),str(self.HOST_DOMAIN))
                            self.Close()
                        
                    else:
                        line1="wrong code"


                    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.Contains(pos):
#                wx.BufferedDC(wx.ClientDC(self),self.closer)
                #self.DShow()
                enter=True
            elif self.wizardRegion.Contains(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 WizardActivation(wx.Frame):
    global enter,line1,line2,line3,keyvalue,postes,users,key,deltatrsp,oscurdir
    def SetNoteShape(self):
        #region=wx.RegionColour(self.bitmap,'#000000',0)
        region = wx.Region(self.bmp)
        self.hasShape=self.SetShape(region)
    def __init__(self, parent, id, title):
        global line1,line2,line3,keyvalue,postes,users,key,oscurdir
        wx.Frame.__init__(self, parent, id, title,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, 'ComicSansMS')

        #self.panel=wx.Panel(self,-1), size=(250, 150)

        self.hasShape=False
        self.delta=(0,0)

        self.image_file = oscurdir+os.sep+'img'+os.sep+'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(oscurdir+os.sep+'img'+os.sep+'code_0.png', wx.BITMAP_TYPE_PNG)
        self.wizard = wx.Bitmap(oscurdir+os.sep+'img'+os.sep+'valider-normal.png', wx.BITMAP_TYPE_PNG)
        #self.wizardf = wx.Bitmap(oscurdir+os.sep+'img'+os.sep+'validerf.png', wx.BITMAP_TYPE_PNG)
        self.wizarda = wx.Bitmap(oscurdir+os.sep+'img'+os.sep+'code_appui.png', wx.BITMAP_TYPE_PNG)
        self.wizardr = wx.Bitmap(oscurdir+os.sep+'img'+os.sep+'code_rollover.png', wx.BITMAP_TYPE_PNG)
        self.close = wx.Bitmap(oscurdir+os.sep+'img'+os.sep+'close-normal.png', wx.BITMAP_TYPE_PNG)
        self.closer = wx.Bitmap(oscurdir+os.sep+'img'+os.sep+'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()

        line2="visit chronosmonitor.com"
        line3="to obtain your server ip"
        enter=False         
        #MyButton(self.panel,-1,(47,168),oscurdir+os.sep+'img'+os.sep+'sync-normal.png',oscurdir+os.sep+'img'+os.sep+'sync-rollover.png',oscurdir+os.sep+'img'+os.sep+'appui-sync.png')
        #self.SetTransparent(220)
        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.Region(self.bitmap)
        self.wizardRegion = wx.Region(self.wizard)
        self.closeRegion = wx.Region(self.close)
        

        self.wizardRegion.Intersect(self.bitmapRegion)
        self.wizardRegion.Offset(60, 100)

        self.closeRegion.Intersect(self.bitmapRegion)
        self.closeRegion.Offset(190, 12)
        keyvalue="mac ossx"

##        try:      
##            regroot=_winreg.HKEY_LOCAL_MACHINE
##            hKey=_winreg.OpenKey(regroot,"SOFTWARE\Microsoft\Cryptography",0,_winreg.KEY_READ)
##            keyvalue, type=_winreg.QueryValueEx(hKey, "MachineGuid")
##        except:
##            keyvalue=""
        #print keyvalue

        self.dc = wx.ClientDC(self)
        self.dc.DrawBitmap(self.bitmap, 0, 0, True)
        #SetNoteShape
        #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=""
        self.OnDraw()

##    def OnClose(self, event):
##        self.tskic.Destroy()
##        self.Destroy()





    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,line3,nkey
        self.dc.DrawBitmap(self.bitmap, 0, 0, True)
        #wx.BufferedPaintDC(self,self.bitmap)
#        wx.BufferedDC(wx.ClientDC(self),self.closer)
        self.dc.SetFont(self.font)
        self.dc.SetTextForeground('WHITE')
        #panel=
        #MyBG(self,-1)
        #panel = MyPanel(self, -1)
        #MyButton(self,-1,(49,168),oscurdir+os.sep+'img'+os.sep+'sync-normal2.png',oscurdir+os.sep+'img'+os.sep+'sync-rollover2.png',oscurdir+os.sep+'img'+os.sep+'appui-sync2.png')
        self.dc.font1 = wx.Font(10, wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_NORMAL, False)
        #self.dc.SetTextBackground(wx.NullColour)
        self.dc.SetTextForeground('WHITE')
        self.dc.SetFont(self.dc.font1)
        #self.dc.SetTextSize(8)
        #self.dc.DrawText("Please enter the server ip :",10,16)
        self.dc.line1=wx.StaticText(self,wx.ID_ANY,label="Please enter the server ip :",pos=(10,16))
        self.dc.line1.SetFont(self.dc.font1)
        self.dc.line1.SetForegroundColour('WHITE')
        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,68)
        self.dc.line2=wx.StaticText(self,wx.ID_ANY,label=str(line2),pos=(10,64))
        self.dc.line2.SetFont(self.dc.font1)
        self.dc.line2.SetForegroundColour('WHITE')
        #self.dc.DrawText(str(line2),10,78)
        self.dc.line3=wx.StaticText(self,wx.ID_ANY,label=str(line3),pos=(10,82))
        self.dc.line3.SetFont(self.dc.font1)
        self.dc.line3.SetForegroundColour('WHITE')
        self.dc.line1.Show()
        self.dc.line2.Show()
        self.dc.line3.Show()
#        self.Show(True)
        #print ('wizard-draw')

    def DShow(self):
        global line1,line2,line3,nkey
#        self.dc.DrawText("Please enter the server ip :",10,16)
 #       self.dc.nkey.SetValue(str(key))
        try:
            self.dc.nkey.Show()
        except:
            pass
        self.dc.line1.Show()
        self.dc.line2.Show()
        self.dc.line3.Show()

#        self.dc.DrawText(str(line1),10,68)
#        self.dc.DrawText(str(line2),10,78)
        #print ('wizard-dshow')
#        self.Show()
        
    def OnPaint(self, event):
        #self.dc = wx.ClientDC(self)
        wx.BufferedPaintDC(self,self.bitmap)
#        wx.BufferedDC(wx.ClientDC(self),self.closer)
        #print ('wizard-paint')
        #self.DShow()
#        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),oscurdir+os.sep+'img'+os.sep+'sync-normal2.png',oscurdir+os.sep+'img'+os.sep+'sync-rollover2.png',oscurdir+os.sep+'img'+os.sep+'appui-sync2.png')
        event.Skip()



    def OnDraw(self):
        #print ('wizard-ondraw-enter')
        wx.BufferedDC(wx.ClientDC(self),self.bitmap)
        self.Draw()
        #self.DShow()
        #print ('wizard-ondraw-end')
        




    def OnLeftDown(self, event):
        global line1,line2,keyvalue,postes,users,key
##        self.bdc = wx.BufferedDC(self.cdc)
        pos = event.GetPosition()
        good=False
##        self.dc.nkey.SelectAll()
##        self.key = self.dc.nkey.GetValue()
##        self.dc.nkey.Clear()
#        print "+"+repr(self.key)+"+"
        if self.closeRegion.Contains(pos):
            self.Close()
        elif self.wizardRegion.Contains(pos):
            #self.dc.DrawBitmap(self.wizardf, 22, 40, True)
            #self.dc.DrawBitmap(self.wizarda, 60, 60, True)
            active=False
            if str(key)=="":
                #wx.BufferedDC(wx.ClientDC(self),self.bitmap)
                self.dc.line2.SetBackgroundColour('#474e6d')
                self.dc.line2.SetForegroundColour('WHITE')
                self.dc.line3.SetBackgroundColour('#474e6d')
                self.dc.line3.SetForegroundColour('WHITE')
                self.dc.line2.SetLabel("it has been send by mail and")
                self.dc.line3.SetLabel("you can find it on your wim account")
            else :
                #try:
                try:
                    if key:
                        conn_string = "host='"+str(key)+"' dbname='chronos-monitor.com' user='chronos' password='gortex855'"
                        conn = psycopg2.connect(conn_string)
                        curs = conn.cursor()
                        result=curs.execute("SELECT serverip,serverdomain FROM users")
                        result=curs.fetchall()
                        u=1
                        postes={}
                        users={}
                        postes['nombre']=0
                        users['nombre']=0
                        if result:
                            for chain in result:
                                users['serverip']=""
                                users['serverdomain']=""
                                p=0
                                for char in chain:
                                    if p==0:users['serverip']=users['serverip']+str(char)
                                    if p==1:users['serverdomain']=users['serverdomain']+str(char)
                                    p=p+1
                            good=True
                            HOST_IP=str(key)
                        else:
                            #wx.BufferedDC(wx.ClientDC(self),self.bitmap)
                            self.dc.line2.SetBackgroundColour('#474e6d')
                            self.dc.line2.SetForegroundColour('WHITE')
                            self.dc.line3.SetBackgroundColour('#474e6d')
                            self.dc.line3.SetForegroundColour('WHITE')
                            self.dc.line2.SetLabel("")
                            self.dc.line3.SetLabel("wrong wim server ip adress")

                        curs.close()
                        conn.close()
                    if good==True:
                        self.Close()
                        try:
                            dialogframe = wx.FindWindowById(474)
                            dialogframe.Close()
                            WizardActivationTwo(None, 474, 'Chronos Monitor',str(HOST_IP))             
                        except:
                            WizardActivationTwo(None, 474, 'Chronos Monitor',str(HOST_IP))  
                except:
                        #wx.BufferedDC(wx.ClientDC(self),self.bitmap)
                        self.dc.line2.SetBackgroundColour('#474e6d')
                        self.dc.line2.SetForegroundColour('WHITE')
                        self.dc.line3.SetBackgroundColour('#474e6d')
                        self.dc.line3.SetForegroundColour('WHITE')
                        self.dc.line2.SetLabel("")
                        self.dc.line2.SetLabel("something wrong")  ##                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.Contains(pos):
                #wx.BufferedDC(wx.ClientDC(self),self.closer)
                #self.SetNoteShape()
                #self.DShow()
                enter=True
            elif self.wizardRegion.Contains(pos):
                #self.dc.DrawBitmap(self.wizardf, 22, 40, True)
                #wx.BufferedDC(wx.ClientDC(self),self.wizardr)
                #self.SetNoteShape()
                #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,deltatrsp,oscurdir
    def __init__(self, parent, id, title):
        global line1,line2,key,dusers,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, 'ComicSansMS')

        #self.panel=wx.Panel(self,-1)

        self.hasShape=False
        self.delta=(0,0)

        self.image_file = oscurdir+os.sep+'img'+os.sep+'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(oscurdir+os.sep+'img'+os.sep+'code_0.png', wx.BITMAP_TYPE_PNG)
        self.wizard = wx.Bitmap(oscurdir+os.sep+'img'+os.sep+'valider-normal.png', wx.BITMAP_TYPE_PNG)
        #self.wizardf = wx.Bitmap(oscurdir+os.sep+'img'+os.sep+'validerf.png', wx.BITMAP_TYPE_PNG)
        self.wizarda = wx.Bitmap(oscurdir+os.sep+'img'+os.sep+'code_appui.png', wx.BITMAP_TYPE_PNG)
        self.wizardr = wx.Bitmap(oscurdir+os.sep+'img'+os.sep+'code_rollover.png', wx.BITMAP_TYPE_PNG)
        self.close = wx.Bitmap(oscurdir+os.sep+'img'+os.sep+'close-normal.png', wx.BITMAP_TYPE_PNG)
        self.closer = wx.Bitmap(oscurdir+os.sep+'img'+os.sep+'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="Please enter the export code :"
        line2="Ask to your administrator"
        enter=False         
        #MyButton(self.panel,-1,(47,168),oscurdir+os.sep+'img'+os.sep+'sync-normal.png',oscurdir+os.sep+'img'+os.sep+'sync-rollover.png',oscurdir+os.sep+'img'+os.sep+'appui-sync.png')
        #self.SetTransparent(220)
        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.Region(self.bitmap)
        self.wizardRegion = wx.Region(self.wizard)
        self.closeRegion = wx.Region(self.close)
        

        self.wizardRegion.Intersect(self.bitmapRegion)
        self.wizardRegion.Offset(60, 100)

        self.closeRegion.Intersect(self.bitmapRegion)
        self.closeRegion.Offset(190, 12)
        keyvalue=""
      
##        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=""
        self.OnDraw()

##    def OnClose(self, event):
##        self.tskic.Destroy()
##        self.Destroy()


    def SetNoteShape(self, *event):
        #region=wx.RegionColour(self.bitmap,'#000000',0)
        region = wx.Region(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),oscurdir+os.sep+'img'+os.sep+'sync-normal2.png',oscurdir+os.sep+'img'+os.sep+'sync-rollover2.png',oscurdir+os.sep+'img'+os.sep+'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("Please enter the export code :",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("Please enter the export code :",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.DShow()
        

##        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),oscurdir+os.sep+'img'+os.sep+'sync-normal2.png',oscurdir+os.sep+'img'+os.sep+'sync-rollover2.png',oscurdir+os.sep+'img'+os.sep+'appui-sync2.png')
        event.Skip()




    def OnDraw(self):
        self.Draw()



    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.Contains(pos):
            self.Close()
        elif self.wizardRegion.Contains(pos):
            #self.dc.DrawBitmap(self.wizardf, 22, 40, True)
            #self.dc.DrawBitmap(self.wizarda, 60, 60, True)
            active=False
            if key=="":
                line1=""
                line2="Please enter the 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="wrong code"

            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.Contains(pos):
                wx.BufferedDC(wx.ClientDC(self),self.closer)
                self.DShow()
                enter=True
            elif self.wizardRegion.Contains(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_Codex(wx.Frame):
    global encodings, liste_encoding,dusers,oscurdir
    def __init__(self, parent, id, title):
        global encodings, liste_encoding,dusers,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, 'ComicSansMS')

        #self.panel=wx.Panel(self,-1)

        self.hasShape=False
        self.delta=(0,0)

        self.image_file = oscurdir+os.sep+'img'+os.sep+'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(oscurdir+os.sep+'img'+os.sep+'parametres_app.png', wx.BITMAP_TYPE_PNG)
        self.closer = wx.Bitmap(oscurdir+os.sep+'img'+os.sep+'parametres_close.png', wx.BITMAP_TYPE_PNG)
        self.close = wx.Bitmap(oscurdir+os.sep+'img'+os.sep+'close-normal.png', wx.BITMAP_TYPE_PNG)
        self.valida = wx.Bitmap(oscurdir+os.sep+'img'+os.sep+'parametres_app.png', wx.BITMAP_TYPE_PNG)
        self.validr = wx.Bitmap(oscurdir+os.sep+'img'+os.sep+'parametres_rollover.png', wx.BITMAP_TYPE_PNG)
        self.valid = wx.Bitmap(oscurdir+os.sep+'img'+os.sep+'valider-normal.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()

 
        enter=False         
        self.SetTransparent(int(deltatrsp))
        encodings={}
        liste_encoding=[]
        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.Region(self.bitmap)
        self.validRegion = wx.Region(self.valid)
        self.closeRegion = wx.Region(self.close)


        self.validRegion.Intersect(self.bitmapRegion)
        self.validRegion.Offset(316, 242)

        self.closeRegion.Intersect(self.bitmapRegion)
        self.closeRegion.Offset(408, 12)
        jak='2164691737824342'

        self.dc = wx.ClientDC(self)
        self.dc.DrawBitmap(self.bitmap, 0, 0, True)
        self.Show(True)


#        self.Fit()
        self.Centre()

        self.OnDraw()
   

    def SetNoteShape(self, *event):
        #region=wx.RegionColour(self.bitmap,'#000000',0)
        region = wx.Region(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 encodings,liste_encoding,oscurdir,ElChaloR,jak
        #print '555'
        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:
            chemFS=oscurdir+os.sep+'wok'+os.sep+'need'+os.sep+'encodings.xml'
            ixim = open(chemFS,'r')
            xim = xml.dom.minidom.parse(ixim)
            ixim.close()
            slap=xim.getElementsByTagName('encoding')
            encodings[0,'encoding']=''
            encodings[0,'alias']=""
            encodings[0,'language']="None"
            liste_encoding.append("None")
            encodings[1,'encoding']=sys.getdefaultencoding()
            encodings[1,'alias']=""
            encodings[1,'language']="workstation system encoding"
            liste_encoding.append('-'+encodings[1,'encoding']+'-'+encodings[1,'language'])
            encodings["total"]=1
            i=2
            for slip in slap:
                encodings[i,'encoding']=slip.getAttribute("encoding")
                encodings[i,'alias']=slip.getAttribute("alias")
                encodings[i,'language']=slip.getAttribute("language")
                encodings["total"]=i
                liste_encoding.append('-'+encodings[i,'encoding']+'-'+encodings[i,'language'])
                #print encodings[i,'language']
                i=i+1
##                class TransPak:
##                    def write(self, data):
##                        ixom.write(data.encode(str(Str_EncoD)))
##                xim.writexml(TransPak(),encoding=str(Str_EncoD))

        except:
                encodings[0,'encoding']=sys.getdefaultencoding()
                encodings[0,'alias']=""
                encodings[0,'language']="workstation system encoding"
                liste_encoding.append('-'+encodings[0,'encoding']+'-'+encodings[0,'language'])
                encodings["total"]=0
        try:
            encodings["Process","Active"]=False
            encodings["Files","Active"]=False
            encodings["Title","Active"]=False
            encodings["Process1"]=""
            encodings["Process1",'alias']=""
            encodings["Process1",'language']=""
            encodings["Process2"]=""
            encodings["Process2",'alias']=""
            encodings["Process2",'language']=""
            encodings["Files1"]=""
            encodings["Files1",'alias']=""
            encodings["Files1",'language']=""
            encodings["Files2"]=""
            encodings["Files2",'alias']=""
            encodings["Files2",'language']=""
            encodings["Title1"]=""
            encodings["Title1",'alias']=""
            encodings["Title1",'language']=""
            encodings["Title2"]=""
            encodings["Title2",'alias']=""
            encodings["Title2",'language']=""
            encodings["Title3"]=""
            encodings["Title3",'alias']=""
            encodings["Title3",'language']=""
            TchemFSF=oscurdir+os.sep+'wok'+os.sep+'conf'+os.sep+'languages.gwh'
            isconfig=os.path.isfile(TchemFSF)
            if isconfig==True:
                fft=open(TchemFSF, mode ='rb')
                output = StringIO.StringIO(fft.read())
                decoutput=StringIO.StringIO()
                fft.close()
                Gdecrypt(output,decoutput)
                lines={}
                p=0
                lines = decoutput.getvalue()
                for char in lines:
                    if char=='\t':
                        p+=1
                        continue
                    if char=='\n':
                        glorb=True
                        break
                    if p==0:
                        encodings["Process1"]=str(encodings["Process1"])+str(char)
                        encodings["Process","Active"]=True
                    if p==1:
                        encodings["Process2"]=str(encodings["Process2"])+str(char)
                        encodings["Process","Active"]=True
                    if p==2:
                        encodings["Files1"]=str(encodings["Files1"])+str(char)
                        encodings["Files","Active"]=True
                    if p==3:
                        encodings["Files2"]=str(encodings["Files2"])+str(char)
                        encodings["Files","Active"]=True
                    if p==4:
                        encodings["Title1"]=str(encodings["Title1"])+str(char)
                        encodings["Title","Active"]=True
                    if p==5:
                        encodings["Title2"]=str(encodings["Title2"])+str(char)
                        encodings["Title","Active"]=True
                    if p==6:
                        encodings["Title3"]=str(encodings["Title3"])+str(char)
                        encodings["Title","Active"]=True
                decoutput.close()
                output.close()
                for i in range(0,int(encodings["total"])+1):
                    if str(encodings[i,'encoding'])==str(encodings["Process1"]):
                        encodings["Process1",'alias']=encodings[i,'alias']
                        encodings["Process1",'language']=encodings[i,'language']
                for i in range(0,int(encodings["total"])+1):
                    if str(encodings[i,'encoding'])==str(encodings["Process2"]):
                        encodings["Process2",'alias']=encodings[i,'alias']
                        encodings["Process2",'language']=encodings[i,'language']
                for i in range(0,int(encodings["total"])+1):
                    if str(encodings[i,'encoding'])==str(encodings["Files1"]):
                        encodings["Files1",'alias']=encodings[i,'alias']
                        encodings["Files1",'language']=encodings[i,'language']
                for i in range(0,int(encodings["total"])+1):
                    if str(encodings[i,'encoding'])==str(encodings["Files2"]):
                        encodings["Files2",'alias']=encodings[i,'alias']
                        encodings["Files2",'language']=encodings[i,'language']
                for i in range(0,int(encodings["total"])+1):
                    if str(encodings[i,'encoding'])==str(encodings["Title1"]):
                        encodings["Title1",'alias']=encodings[i,'alias']
                        encodings["Title1",'language']=encodings[i,'language']
                for i in range(0,int(encodings["total"])+1):
                    if str(encodings[i,'encoding'])==str(encodings["Title2"]):
                        encodings["Title2",'alias']=encodings[i,'alias']
                        encodings["Title2",'language']=encodings[i,'language']
                for i in range(0,int(encodings["total"])+1):
                    if str(encodings[i,'encoding'])==str(encodings["Title3"]):
                        encodings["Title3",'alias']=encodings[i,'alias']
                        encodings["Title3",'language']=encodings[i,'language']

        except:
                encodings["Process1"]=sys.getdefaultencoding()
                encodings["Process1",'alias']=""
                encodings["Process1",'language']="workstation system encoding"
                encodings["Process2"]=""
                encodings["Process2",'alias']=""
                encodings["Process2",'language']=""
                encodings["Files1"]=sys.getdefaultencoding()
                encodings["Files1",'alias']=""
                encodings["Files1",'language']="workstation system encoding"
                encodings["Files2"]=""
                encodings["Files2",'alias']=""
                encodings["Files2",'language']=""
                encodings["Title1"]=sys.getdefaultencoding()
                encodings["Title1",'alias']=""
                encodings["Title1",'language']="workstation system encoding"
                encodings["Title2"]=""
                encodings["Title2",'alias']=""
                encodings["Title2",'language']=""
                encodings["Title3"]=""
                encodings["Title3",'alias']=""
                encodings["Title3",'language']=""
                #print 'encoding 0'



    def OnEncod1Select(self,event):
        global Tencod,encodings
        encod=event.GetId()
        encod = wx.FindWindowById(int(encod))
        Tencod=encod.GetValue()
        for i in range(0,int(encodings["total"])+1):
            if encodings[i,'encoding'] in Tencod:
                encodings["Process1"]=encodings[i,'encoding']
                #print ('tencod-'+encodings["Process1"])
    def OnEncod2Select(self,event):
        global Tencod,encodings
        encod=event.GetId()
        encod = wx.FindWindowById(int(encod))
        Tencod=encod.GetValue()
        for i in range(0,int(encodings["total"])+1):
            if encodings[i,'encoding'] in Tencod:
                encodings["Process2"]=encodings[i,'encoding']


    def OnEncod3Select(self,event):
        global Tencod,encodings
        encod=event.GetId()
        encod = wx.FindWindowById(int(encod))
        Tencod=encod.GetValue()
        for i in range(0,int(encodings["total"])+1):
            if encodings[i,'encoding'] in Tencod:
                encodings["Files1"]=encodings[i,'encoding']

    def OnEncod4Select(self,event):
        global Tencod,encodings
        encod=event.GetId()
        encod = wx.FindWindowById(int(encod))
        Tencod=encod.GetValue()
        for i in range(0,int(encodings["total"])+1):
            if encodings[i,'encoding'] in Tencod:
                encodings["Files2"]=encodings[i,'encoding']
    def OnEncod5Select(self,event):
        global Tencod,encodings
        encod=event.GetId()
        encod = wx.FindWindowById(int(encod))
        Tencod=encod.GetValue()
        for i in range(0,int(encodings["total"])+1):
            if encodings[i,'encoding'] in Tencod:
                encodings["Title1"]=encodings[i,'encoding']


    def OnEncod6Select(self,event):
        global Tencod,encodings
        encod=event.GetId()
        encod = wx.FindWindowById(int(encod))
        Tencod=encod.GetValue()
        for i in range(0,int(encodings["total"])+1):
            if encodings[i,'encoding'] in Tencod:
                encodings["Title2"]=encodings[i,'encoding']

    def OnEncod7Select(self,event):
        global Tencod,encodings
        encod=event.GetId()
        encod = wx.FindWindowById(int(encod))
        Tencod=encod.GetValue()
        for i in range(0,int(encodings["total"])+1):
            if encodings[i,'encoding'] in Tencod:
                encodings["Title3"]=encodings[i,'encoding']
    def Draw(self):
        global liste_encoding,dusers
        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 = scrolled.ScrolledPanel( self,-1,(10,50),(420,190), style=wx.SUNKEN_BORDER)
        self.dc.panel.SetupScrolling(scroll_x=True,scroll_y=True)
        self.dc.panel.SetBackgroundColour("#D5D5D5")
        if dusers['config']=="1":
            self.dc.text1=wx.StaticText(self.dc.panel, 20002, 'Software',pos=(5,5))
            self.dc.langu1 = wx.ComboBox(self.dc.panel, 20001, choices=liste_encoding,
                                         style=wx.CB_READONLY | wx.EXPAND ,pos=(60,5),size=(340, 24))
            self.dc.langu1.Bind(wx.EVT_COMBOBOX, self.OnEncod1Select)
            self.dc.langu1.SetValue(str('-'+encodings['Process1']+'-'+encodings["Process1",'language']))
            self.dc.langu2 = wx.ComboBox(self.dc.panel, 20004, choices=liste_encoding,
                                         style=wx.CB_READONLY | wx.EXPAND ,pos=(60,25),size=(340, 24))
            self.dc.langu2.Bind(wx.EVT_COMBOBOX, self.OnEncod2Select)
            self.dc.langu2.SetValue(str('-'+encodings['Process2']+'-'+encodings["Process2",'language']))
            self.dc.text2=wx.StaticText(self.dc.panel, 20005, 'Files',pos=(5,55))
            self.dc.langu3 = wx.ComboBox(self.dc.panel, 20006, choices=liste_encoding,
                                         style=wx.CB_READONLY | wx.EXPAND ,pos=(60,55),size=(340, 24))
            self.dc.langu3.Bind(wx.EVT_COMBOBOX, self.OnEncod3Select)
            self.dc.langu3.SetValue(str('-'+encodings['Files1']+'-'+encodings["Files1",'language']))
            self.dc.langu4 = wx.ComboBox(self.dc.panel, 20007, choices=liste_encoding,
                                         style=wx.CB_READONLY | wx.EXPAND ,pos=(60,75),size=(340, 24))
            self.dc.langu4.Bind(wx.EVT_COMBOBOX, self.OnEncod4Select)
            self.dc.langu4.SetValue(str('-'+encodings['Files2']+'-'+encodings["Files2",'language']))
            self.dc.langu3.Bind(wx.EVT_COMBOBOX, self.OnEncod3Select)
            self.dc.text3=wx.StaticText(self.dc.panel, 20008, 'Window',pos=(5,105))
            self.dc.langu5 = wx.ComboBox(self.dc.panel, 20009, choices=liste_encoding,
                                         style=wx.CB_READONLY | wx.EXPAND ,pos=(60,105),size=(340, 24))
            self.dc.langu5.Bind(wx.EVT_COMBOBOX, self.OnEncod5Select)            
            self.dc.langu5.SetValue(str('-'+encodings['Title1']+'-'+encodings["Title1",'language']))
            self.dc.langu6 = wx.ComboBox(self.dc.panel, 20010, choices=liste_encoding,
                                         style=wx.CB_READONLY | wx.EXPAND ,pos=(60,125),size=(340, 24))
            self.dc.langu6.Bind(wx.EVT_COMBOBOX, self.OnEncod6Select)
            self.dc.langu6.SetValue(str('-'+encodings['Title2']+'-'+encodings["Title2",'language']))
            self.dc.langu7 = wx.ComboBox(self.dc.panel, 20011, choices=liste_encoding,
                                         style=wx.CB_READONLY | wx.EXPAND ,pos=(60,145),size=(340, 24))
            self.dc.langu7.Bind(wx.EVT_COMBOBOX, self.OnEncod7Select)
            self.dc.langu7.SetValue(str('-'+encodings['Title3']+'-'+encodings["Title3",'language']))

            self.dc.message=wx.StaticText(self.dc.panel, 20013, '',pos=(10,165))
            #self.dc.encod3.SetValue('')
        self.Show ( True )
        
    def OnPaint(self, event):

        wx.BufferedPaintDC(self,self.bitmap)

        event.Skip()

    def OnDraw(self):
        self.chargeConfig()
        self.Draw()        


    def verifyTransparency(self):
        global vtp,dtp,message
        message=""
        try:
            if (str(encodings["Process1"])!='Aucun') and (str(encodings["Process1"])!='')and(str(encodings["Files1"])!='Aucun') and (str(encodings["Files1"])!='')and(str(encodings["Title1"])!='Aucun') and (str(encodings["Title1"])!=''):
                vtp="OK"
            else:
                vtp="NOT"
                message="Please Choose at least one Language per item"
        except:
            vtp="NOT"
            message="Please Choose at least one Language per item"
            

    def saveConfig(self):
        global oscurdir,encodings
        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()
        vtp="NOT"
        message="erreur lors de l'enregistrement de la configuration"
        TchemFSF=oscurdir+os.sep+'wok'+os.sep+'conf'+os.sep+'languages.gwh'
        strin=str(encodings["Process1"])+'\t'+str(encodings["Process2"])+'\t'+str(encodings["Files1"])+'\t'+str(encodings["Files2"])+'\t'+str(encodings["Title1"])+'\t'+str(encodings["Title2"])+'\t'+str(encodings["Title3"])+'\n'
        #print (repr(strin))
        output = StringIO.StringIO(strin)
        Gencrypt(output,TchemFSF)
        message=""
        vtp="OK"
        
    def OnLeftDown(self, event):
        global message,vtp,line1,line2,line3,reset,ssyncro,analyse,question,dtp,dina,jak,ElChaloR,oscurdir,deltatrsp
        #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.Contains(pos):
            self.Close()
        elif self.validRegion.Contains(pos):
            #wx.BufferedDC(wx.ClientDC(self),self.valida)
            if dusers['config']=="1":
##                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(ssyncro)+'\t'+str(analyse)+'\t'+str(question)+'\t'+str(dtp)+'\t'+str(dina)+'\n'
##                output = StringIO.StringIO(strin)
##                Gencrypt(output,TchemFSF)
##                message=""
                self.verifyTransparency()
                try:
                    if str(vtp)=="OK":self.saveConfig()
                    else :self.dc.message.SetLabel(message)
                    try:
                        if str(vtp)=="OK":
                            reset=True
                            line1="Settings Saved"
                            line2="Immediatly Take Effect"
                            line3=""
                            self.Close()
                            try:
                                dialogframe = wx.FindWindowById(465)
                                dialogframe.Close()
                                WizardEnd(None, 475, 'Chronos Monitor Parametres')            
                            except:
                                WizardEnd(None, 475, '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.Contains(pos):
            #wx.BufferedDC(wx.ClientDC(self),self.closer)
            enter=True
        elif self.validRegion.Contains(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 Parametres(wx.Frame):
    global invisible,on_open,dusers,reset,jak,dina,message,vtp,line1,line2,line3,ElChaloR,oscurdir,ssyncro,analyse,question,deltatrsp,user,users
    def __init__(self, parent, id, title):
        global invisible,on_open,dusers,reset,jak,dina,message,vtp,line1,line2,line3,ElChaloR,oscurdir,ssyncro,analyse,question,deltatrsp,user,listeuser,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(11, wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL, 
		wx.FONTWEIGHT_BOLD, False, 'ComicSansMS')

        #self.panel=wx.Panel(self,-1)

        self.hasShape=False
        self.delta=(0,0)

        self.image_file = oscurdir+os.sep+'img'+os.sep+'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(oscurdir+os.sep+'img'+os.sep+'parametres_app.png', wx.BITMAP_TYPE_PNG)
        self.closer = wx.Bitmap(oscurdir+os.sep+'img'+os.sep+'parametres_close.png', wx.BITMAP_TYPE_PNG)
        self.close = wx.Bitmap(oscurdir+os.sep+'img'+os.sep+'close-normal.png', wx.BITMAP_TYPE_PNG)
        self.valida = wx.Bitmap(oscurdir+os.sep+'img'+os.sep+'parametres_app.png', wx.BITMAP_TYPE_PNG)
        self.validr = wx.Bitmap(oscurdir+os.sep+'img'+os.sep+'parametres_rollover.png', wx.BITMAP_TYPE_PNG)
        self.valid = wx.Bitmap(oscurdir+os.sep+'img'+os.sep+'valider-normal.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()

 
        enter=False         
        self.SetTransparent(int(deltatrsp))
        listeuser=[]
        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.Region(self.bitmap)
        self.validRegion = wx.Region(self.valid)
        self.closeRegion = wx.Region(self.close)


        self.validRegion.Intersect(self.bitmapRegion)
        self.validRegion.Offset(316, 242)

        self.closeRegion.Intersect(self.bitmapRegion)
        self.closeRegion.Offset(408, 12)
        jak='2164691737824342'

        self.dc = wx.ClientDC(self)
        self.dc.DrawBitmap(self.bitmap, 0, 0, True)
        self.Show(True)
#        self.Fit()
        self.Centre()

        self.OnDraw()

    def SetNoteShape(self, *event):
        #region=wx.RegionColour(self.bitmap,'#000000',0)
        region = wx.Region(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 invisible,on_open,user,deltatrsp,oscurdir,jak,ElChaloR,ssyncro,analyse,question,dinac,dtp,dina,slogpath,syncrotip,sconauto,listeuser,slogrep,Tuser
        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'
            isconfig=os.path.isfile(TchemFSF)
            if isconfig==True:
                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=""
                syncrotip=""
                slogrep=""
                slogpath=""
                sconauto=""
                on_open=""
                invisible=""
                Tuser=""
                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
                    if p==5:
                        syncrotip=syncrotip+char
                    if p==6:
                        slogrep=slogrep+char
                    if p==7:
                        slogpath=slogpath+char
                    if p==8:
                        sconauto=sconauto+char
                    if p==9:
                        Tuser=Tuser+char
                    if p==10:
                        on_open=on_open+char
                    if p==11:
                        invisible=invisible+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
                    if syncrotip=="True":syncrotip='cont'
                    if slogrep=="True":slogrep=True
                    else:slogrep=False
                    if sconauto=="True":sconauto=True
                    else:sconauto=False
                    if on_open=="True":on_open=True
                    else:on_open=False
                    if invisible=="True":invisible=False
                    else:invisible=False
                    deltatrsp=tdeltatrsp
                    dtp=tdeltatrsp
                    dinac=tdinac
                    dina=dinac
                    self.SetTransparent(int(deltatrsp))
                    listeuser.append('')
                    for x in range(1,user["nombre"]):
                        listeuser.append(user["nom",x]+' '+user["prenom",x])
                    self.Show(True)
                else:
                    question=False
                    analyse=False
                    ssyncro=False
                    syncrotip='inact'
                    slogrep=False
                    sconauto=False
                    slogpath=oscurdir+os.sep+'wok'+os.sep+'enc'
                    Tuser=''
                    listeuser.append('')
                    for x in range(1,user["nombre"]):
                        listeuser.append(user["nom",x]+' '+user["prenom",x])
                    deltatrsp=255
                    dinac=60
                    dtp=deltatrsp
                    dina=dinac
                    on_open=False
                    invisible=False
            else:
                question=False
                analyse=False
                ssyncro=False
                syncrotip='inact'
                slogrep=False
                sconauto=False
                slogpath=oscurdir+os.sep+'wok'+os.sep+'enc'
                Tuser=''
                listeuser.append('')
                for x in range(1,user["nombre"]):
                    listeuser.append(user["nom",x]+' '+user["prenom",x])
                deltatrsp=255
                dinac=60
                dtp=deltatrsp
                dina=dinac
                on_open=False
                invisible=False
        except:
            question=False
            analyse=False
            ssyncro=False
            syncrotip='inact'
            slogrep=False
            sconauto=False
            slogpath=oscurdir+os.sep+'wok'+os.sep+'enc'
            Tuser=''
            listeuser.append('')
            for x in range(1,user["nombre"]):
                listeuser.append(user["nom",x]+' '+user["prenom",x])
            deltatrsp=255
            dinac=60
            dtp=deltatrsp
            dina=dinac
            on_open=False
            invisible=False


    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 desinstalle(self,event):
        global dusers,line1,line2,line3
        if dusers['config']=="1":
            try:
                uninstallframe = wx.FindWindowById(473)
                if uninstallframe.IsShown():
                    uninstallframe.Show()
            except:
                line1="Do you really want"
                line2="to disable work station ?"
                line3=""
                UnInstall(None, 473, '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 ssyncro
        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():
            ssyncro=True
        else:
            ssyncro=False

    def OnRadioCheck(self,event):
        global syncrotip
##        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 self.dc.radio_syncro_cont.GetValue()==True:
            syncrotip= 'cont'
        if self.dc.radio_syncro_inact.GetValue()==True:
            syncrotip= 'inact'
        if self.dc.radio_syncro_manu.GetValue()==True:
            syncrotip= 'manu'
##        tsyncro= user.GetValue()
##        print tsyncro
##            sviewer=True
##        else:
##            sviewer=False
    def codex(self,event):
        global dusers
        if dusers['config']=="1":
            try:
                codexframe = wx.FindWindowById(475)
                if codexframe.IsShown():
                    codexframe.Show()
            except:
                Parametres_Codex(None, 475, 'Chronos Monitor')
                
    def OnLogRepCheck(self,event):
        global slogrep
        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():
            slogrep=True
            self.dc.logpath.Show()
            self.dc.nodir.Show()
        else:
            slogrep=False
            self.dc.logpath.Hide()
            self.dc.nodir.Hide()

    def OnConAutoCheck(self,event):
        global sconauto
        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():
            sconauto=True
            self.dc.conauto.Show()
        else:
            sconauto=False
            self.dc.conauto.Hide()          

    def OnUserSelect(self,event):
        global Tuser
        uzer=event.GetId()
        user = wx.FindWindowById(int(uzer))
        Tuser=user.GetValue()
        
    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 OnPathSelect(self,event):
        global slogpath
        slogpath=event.GetString()

    def OnReduceCheck(self,event):
        global on_open
        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():
            on_open=True
        else:
            on_open=False


    def InvisibleMode(self,event):
        global invisible
        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():
            invisible=True
        else:
            invisible=False        

    def bakPath(self,event):
        global slogpath
        openFileDialog = wx.DirDialog(None, "Choose a directory:",style=wx.DD_DEFAULT_STYLE | wx.DD_NEW_DIR_BUTTON)
        if openFileDialog.ShowModal() == wx.ID_CANCEL:
            return
        if openFileDialog.ShowModal() == wx.ID_OK:
            slogpath=openFileDialog.GetPath()
        openFileDialog.Destroy() 
        self.dc.logpath.SetValue(slogpath)
        
    def Draw(self):
        global ssyncro,analyse,question,deltatrsp,dinac,syncrotip,slogrep,sconauto,slogpath,listeuser,on_open,invisible
        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 = scrolled.ScrolledPanel( self,-1,(10,50),(420,190), style=wx.SUNKEN_BORDER)
        self.dc.panel.SetupScrolling(scroll_x=True,scroll_y=True)
        self.dc.panel.SetBackgroundColour("#D5D5D5")
        if dusers['config']=="1":
            self.dc.boxdossiers=wx.CheckBox(self.dc.panel,30001,label='Files Watch',pos=(3,5))
            self.dc.boxdossiers.Bind(wx.EVT_CHECKBOX, self.OnSyncroCheck)
            self.dc.boxdossiers.SetValue(ssyncro)
            self.dc.uninstall = wx.Button ( self.dc.panel, 30011, 'UnInstall' ,pos=(100,0))
            self.dc.uninstall.Bind(wx.EVT_BUTTON, self.desinstalle )
            self.dc.codex = wx.Button ( self.dc.panel, 30012, 'Languages' ,pos=(200,0))
            self.dc.codex.Bind(wx.EVT_BUTTON, self.codex )
            if dusers['export']=="1" or dusers['export']=="m":
                self.dc.export = wx.Button ( self.dc.panel, 30013, 'Export' ,pos=(300,0))
                self.dc.export.Bind(wx.EVT_BUTTON, self.Export )
            self.dc.boxonopen=wx.CheckBox(self.dc.panel,30002,label="Minimize on open",pos=(200,40))
            self.dc.boxonopen.Bind(wx.EVT_CHECKBOX, self.OnReduceCheck)
            self.dc.boxonopen.SetValue(on_open)
            self.dc.boxinvisible=wx.CheckBox(self.dc.panel,30010,label="Invisible mode",pos=(200,60))
            self.dc.boxinvisible.Bind(wx.EVT_CHECKBOX, self.InvisibleMode)
            self.dc.boxinvisible.SetValue(invisible)
            self.dc.boxanalyse=wx.CheckBox(self.dc.panel,30004,label='Analysis on synchronize',pos=(3,20))
            self.dc.boxanalyse.Bind(wx.EVT_CHECKBOX, self.OnAnalyseCheck)
            self.dc.boxanalyse.SetValue(analyse)
            self.dc.radio_syncro_cont=wx.RadioButton(self.dc.panel,-1,label='constant synchronization',pos=(3,40))
            self.dc.radio_syncro_cont.Bind(wx.EVT_RADIOBUTTON, self.OnRadioCheck)
            self.dc.radio_syncro_inact=wx.RadioButton(self.dc.panel,-1,label='on inactivity synchronisation',pos=(3,55))
            self.dc.radio_syncro_inact.Bind(wx.EVT_RADIOBUTTON, self.OnRadioCheck)
            self.dc.radio_syncro_manu=wx.RadioButton(self.dc.panel,-1,label='manual synchronisation',pos=(3,70))
            self.dc.radio_syncro_manu.Bind(wx.EVT_RADIOBUTTON, self.OnRadioCheck)
            if syncrotip=='cont':self.dc.radio_syncro_cont.SetValue(True)
            if syncrotip=='inact':self.dc.radio_syncro_inact.SetValue(True)
            if syncrotip=='manu':self.dc.radio_syncro_manu.SetValue(True)
##            self.dc.postbox.Add(self.dc.radio[x],wx.LEFT)
##            if int(postes['selected'])==int(x):
##                self.dc.radio[x].SetValue(True)
##                posteid=postes['ID',x]
##                postehip=x;
##            self.dc.boxviewer=wx.CheckBox(self.dc.panel,30004,label='synchronisation pour le viewer',pos=(3,50))
##            self.dc.boxviewer.Bind(wx.EVT_CHECKBOX, self.OnViewerCheck)
##            self.dc.boxviewer.SetValue(sviewer)
            self.dc.boxlogrep=wx.CheckBox(self.dc.panel,30005,label='Specific Logs Folder',pos=(3,90))
            self.dc.boxlogrep.Bind(wx.EVT_CHECKBOX, self.OnLogRepCheck)
            self.dc.boxlogrep.SetValue(slogrep)            
            self.dc.logpath=wx.TextCtrl(self.dc.panel, 30008, value=slogpath,size=(85, -1),pos=(163,87))
            self.dc.logpath.Bind(wx.EVT_TEXT, self.OnPathSelect)
            self.dc.logpath.SetValue(slogpath)
            self.dc.nodir = wx.Button ( self.dc.panel, 100, 'Logs Folder' ,pos=(253,85))
            self.dc.nodir.Bind(wx.EVT_BUTTON, self.bakPath )
            if slogrep==False:
                self.dc.logpath.Hide()
                self.dc.nodir.Hide()
            self.dc.boxconauto=wx.CheckBox(self.dc.panel,30006,label='automatic connection on startup',pos=(3,110))
            self.dc.boxconauto.Bind(wx.EVT_CHECKBOX, self.OnConAutoCheck)
            self.dc.boxconauto.SetValue(sconauto)
            self.dc.conauto = wx.ComboBox(self.dc.panel, 30009, choices=listeuser, style=wx.CB_READONLY | wx.EXPAND ,pos=(233,110))
            self.dc.conauto.Bind(wx.EVT_COMBOBOX, self.OnUserSelect)
            self.dc.conauto.SetValue(Tuser)
            if sconauto==False:
                self.dc.conauto.Hide()
            self.dc.boxquestion=wx.CheckBox(self.dc.panel,30003,label='question after inactivity',pos=(3,130))
            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),pos=(374,130))
            self.dc.transparence.SetEditable(True)
            self.dc.transparence.Bind(wx.EVT_TEXT, self.OnTTexT)
            self.dc.transparencetxt = wx.StaticText(self.dc.panel, -1, '/ Transparency degree (0-255)',pos=(174,130))
            try:
                delae=int(dinac)
                self.dc.delai=wx.TextCtrl(self.dc.panel,wx.ID_ANY,str(delae),size=(40,21),pos=(163,146))
            except:
                self.dc.delai=wx.TextCtrl(self.dc.panel,wx.ID_ANY,"4",size=(40,21),pos=(163,146))
            self.dc.delai.SetEditable(True)
            self.dc.delai.Bind(wx.EVT_TEXT, self.OnDTexT)
            self.dc.delaitxt = wx.StaticText(self.dc.panel, -1, "inactivity delay (minutes)",pos=(3,146))
            self.dc.message = wx.StaticText(self.dc.panel, -1, '',pos=(3,170))


        self.Show ( True )
        
    def OnPaint(self, event):

        wx.BufferedPaintDC(self,self.bitmap)

        event.Skip()

    def OnDraw(self):
        self.chargeConfig()
        self.Draw()        


    def verifyTransparency(self):
        global vtp,dtp,message
        message=""
        try:
            if (int(dtp)>=0) and (int(dtp)<=255):
                vtp="OK"
                message="Attention the 0 degree makes completely transparent your windows"
            else:
                vtp="NOT"
                message="The transparency degree's number has to be between 0 and 255"
        except:
            vtp="NOT"
            message="The transparency degree's number has to be between 0 and 255"
            

    def verifyDina(self):
        global dina,vtp,message
        try:
            if int(dina)>=0:
                pass
            else:
                vtp="NOT"
                message="Inactivity time has to be a number upper than 0"
        except:
            vtp="NOT"
            message="Inactivity time has to be a number upper than 0"

    def verifyUser(self):
        global sconauto,vtp,message,Tuser
        try:
            if sconauto==True and Tuser=='':
                vtp="NOT"
                message="You had to choose user for the automatic connection"
        except:
            vtp="NOT"
            message="You had to choose user for the automatic connection"

    def verifyRep(self):
        global slogrep,vtp,message,slogpath
        try:
            if slogrep==True and slogpath=='':
                vtp="NOT"
                message="You had to fill path of Logs folder"
            else:
                repto=slogpath+os.sep+'test.txt'
                trylogfile = open(repto, mode ='w')
                trylogfile.close()
                os.remove(repto)
        except:
            vtp="NOT"
            message="Indicated Folders does'nt work please verify permissions"
            
    def verifyInvisible(self):
        global invisible,sconauto,oscurdir
        try:
            if sconauto==False and invisible==True:
                vtp="NOT"
                message="Le mode invisible requiert la connection automatique au demarrage"
            elif sconauto==True and invisible==True:
                try:
                    TchemMSF=oscurdir+os.sep+'wok'+os.sep+'conf'+os.sep+'hrd.gwh'
                    invfile = open(TchemMSF, 'w+')
                    invfile.close()
                except:
                    vtp="NOT"
                    message="Le repertoire" + str(oscurdir)+"\wok\conf\ est inacccessible, vérifiez les droits"
        except:
            vtp="NOT"
            message="Vous devez selectionner un utilisateur pour la connection automatique"
            
    def saveConfig(self):
        global invisible,on_open,ssyncro,analyse,question,dtp,dina,jak,ElChaloR,oscurdir,message,deltatrsp,vtp,slogpath,syncrotip,sconauto,slogrep,Tuser
        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()
        vtp="NOT"
        message="error during configuration registration"
        TchemFSF=oscurdir+os.sep+'wok'+os.sep+'conf'+os.sep+'config.gwh'
        strin=str(ssyncro)+'\t'+str(analyse)+'\t'+str(question)+'\t'+str(dtp)+'\t'+str(dina)+'\t'+str(syncrotip)+'\t'+str(slogrep)+'\t'+str(slogpath)+'\t'+str(sconauto)+'\t'+str(Tuser)+'\t'+str(on_open)+'\t'+str(invisible)+'\n'
        output = StringIO.StringIO(strin)
        Gencrypt(output,TchemFSF)
        message=""
        vtp="OK"
        
    def OnLeftDown(self, event):
        global message,vtp,line1,line2,line3,reset,ssyncro,analyse,question,dtp,dina,jak,ElChaloR,oscurdir,deltatrsp
        #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.Contains(pos):
            self.Close()
        elif self.validRegion.Contains(pos):
            #wx.BufferedDC(wx.ClientDC(self),self.valida)
            if dusers['config']=="1":
##                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(ssyncro)+'\t'+str(analyse)+'\t'+str(question)+'\t'+str(dtp)+'\t'+str(dina)+'\n'
##                output = StringIO.StringIO(strin)
##                Gencrypt(output,TchemFSF)
##                message=""
                self.verifyTransparency()
                self.verifyDina()
                self.verifyUser()
                self.verifyRep()
                self.verifyInvisible()
                try:
                    if str(vtp)=="OK":self.saveConfig()
                    else :self.dc.message.SetLabel(message)
                    try:
                        if str(vtp)=="OK":
                            reset=True
                            line1="Configuration saved."
                            line2="Please run WIM again"
                            line3="for configuration update"
                            self.Close()
                            try:
                                dialogframe = wx.FindWindowById(465)
                                dialogframe.Close()
                                WizardEnd(None, 465, 'Chronos Monitor Parametres')            
                            except:
                                WizardEnd(None, 465, '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.Contains(pos):
            #wx.BufferedDC(wx.ClientDC(self),self.closer)
            enter=True
        elif self.validRegion.Contains(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 HOST_IP,jak,dina,message,vtp,line1,line2,line3,ElChaloR,oscurdir,filtre,Tcontenant,Tcontenu,Tpropriete,Tfiltre,Tclient,Tprestation,Tprestationid,xlisteclient,xlisteactivite,listetache,deltatrsp,users
    def __init__(self, parent, id, title,messagem):
        global HOST_IP,jak,dina,message,vtp,line1,line2,line3,ElChaloR,oscurdir,filtre,Tcontenant,Tcontenu,Tpropriete,Tfiltre,Tclient,Tprestation,Tprestationid,xlisteclient,xlisteactivite,listetache,deltatrsp,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(11, wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL, 
		wx.FONTWEIGHT_BOLD, False, 'ComicSansMS')

        #self.panel=wx.Panel(self,-1)

        self.hasShape=False
        self.delta=(0,0)

        self.image_file = oscurdir+os.sep+'img'+os.sep+'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(oscurdir+os.sep+'img'+os.sep+'analyse-rollover.png', wx.BITMAP_TYPE_PNG)
        self.closer = wx.Bitmap(oscurdir+os.sep+'img'+os.sep+'analyse-close.png', wx.BITMAP_TYPE_PNG)
        self.close = wx.Bitmap(oscurdir+os.sep+'img'+os.sep+'close-normal.png', wx.BITMAP_TYPE_PNG)
        self.valida = wx.Bitmap(oscurdir+os.sep+'img'+os.sep+'analyse-appui.png', wx.BITMAP_TYPE_PNG)
        self.validr = wx.Bitmap(oscurdir+os.sep+'img'+os.sep+'analyse-rollover.png', wx.BITMAP_TYPE_PNG)
        self.valid = wx.Bitmap(oscurdir+os.sep+'img'+os.sep+'valider-normal.png', wx.BITMAP_TYPE_PNG)
        self.fond = wx.Bitmap(oscurdir+os.sep+'img'+os.sep+'analyse-fond.png', wx.BITMAP_TYPE_PNG)

        filtre={}
        checkfichier={}
        jak='2164691737824342'
        filtre['nombre']=0
        Tcontenant=""
        Tcontenu=""
        Tpropriete=""
        Tfiltre=""
        Tclient=""
        Tprestation=""
        Ttache=""
        Tprestationid=""
        xlisteclient = ['','undefined']
        xlisteactivite = ['','undefined']
        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="Please visit:"
        line2="http://www.chronosmonitor.fr"
        line3="to obtain activation key"  
        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.Region(self.bitmap)
        self.validRegion = wx.Region(self.valid)
        self.closeRegion = wx.Region(self.close)


        self.validRegion.Intersect(self.bitmapRegion)
        self.validRegion.Offset(316, 242)

        self.closeRegion.Intersect(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()

        self.OnDraw()

    def SetNoteShape(self, *event):
        #region=wx.RegionColour(self.bitmap,'#000000',0)
        region = wx.Region(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 importexport(self,event):
        try:
            dialogframe = wx.FindWindowById(472)
            dialogframe.Show()           
        except: 
            AnalyseIE(None, 472, 'Chronos Monitor Analysis Import Export','Select filters to import/export')

    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=uzer
##        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)] + ": IF "+filtre["Contenant",int(hip)] )
        self.dc.contenutxt.SetLabel(filtre["Propriete",int(hip)] + ' "'+  filtre["Contenu",int(hip)]+'"' )
        self.dc.clienttxt.SetLabel("Then Customer = " + filtre["Client",int(hip)] )
        self.dc.activitetxt.SetLabel("Service = " + filtre["Prestation",int(hip)] )

    def chargeFiltres(self):
        global filtre,message
        try:
            try:
                chemFS= oscurdir + os.sep + "wok"+os.sep+ "conf"+os.sep+"gaors.gwh"
                isfiltre=os.path.isfile(chemFS)
                if isfiltre==True:
                    logfile = open(chemFS,'rb')
                else:
                    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"                    
            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="error during filter loading"
                
    def chargeDonnees(self):
        global listeclient,listeactivite,message,poste,presta,users,HOST_IP
        try:
            TchemFSF=oscurdir+os.sep+'wok'+os.sep+'conf'+os.sep+'local.gwh'
            isconfig=os.path.isfile(TchemFSF)
            if isconfig==True:
                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
                ip_enter=False
                go_on=True
                for char in lines:
                    if char=='\t':
                        p+=1
                        continue
                    if char=='\n':
                        break
                    if p==0 and l==0 and char in ['i','p',':']:
                        ip_enter=True
                        go_on=False
                        continue
                    if go_on==False:
                        if ip_enter==True and p==0 and l==0:
                            users['serverip']=users['serverip']+char
                        if p==1 and l==0:users['serverdomain']+char
                        if p==2 and l==0:poste["PID"]=poste["PID"]+char
                        if p==3 and l==0:poste["ID"]=poste["ID"]+char
                        if p==4 and l==0:poste["posteNAME"]=poste["posteNAME"]+char
                        if p==5 and l==0:poste["Date"]=poste["Date"]+char
                        if p==6 and l==0:poste["GUID"]=poste["GUID"]+char
                        if p==7 and l==0:poste["ADMINID"]=poste["ADMINID"]+char
                    else:
                        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
                        users['serverip']='88.191.122.246'
                        users['serverdomain']='http://www.chronosmonitor.com'                        
                if poste["ADMINID"]!="":    
                    conn_string = "host='"+str(HOST_IP)+"' dbname='chronos-monitor.com' user='chronos' password='gortex855'"
                    conn = psycopg2.connect(conn_string)
                    curs = conn.cursor()
                    result=curs.execute("SELECT nomsoc FROM clients WHERE idadmin='"+str(poste["ADMINID"])+"';" )
                    result=curs.fetchall()
                    xlisteclient.append('Customer mentioned')
                    if result:
                        for chain in result:
                            Tclient=""
                            for char in chain:
                                Tclient=Tclient+str(char)
                            xlisteclient.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
                    xlisteactivite.append('Service mentioned')
                    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
                            xlisteactivite.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
                                    xlisteactivite.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
                                            xlisteactivite.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="error : run configuration wizard before"
            else:
                 message="error : run configuration wizard before"
        except:
            message="Internet connection required"
        

    def ajouteFiltre(self,event):
        global Tcontenant,Tcontenu,Tpropriete,Tfiltre,Tclient,Tprestation,xlisteclient,xlisteactivite,listetache,message,filtre,fbox
        tpass=False
        if Tcontenant!="":
            tpass=True
        else:
            self.dc.message.SetLabel("Please choose container")
        if tpass==False:
            return
        tpass=False
        if Tpropriete!="":
            tpass=True
        else:
            self.dc.message.SetLabel("Please choose property")
        if tpass==False:
            return
        tpass=False
        if Tfiltre!="":
            tpass=True
        else:
            self.dc.message.SetLabel("Please enter a title to filter")
        if tpass==False:
            return
        tpass=False
        if Tcontenu!="":
            tpass=True
        else:
            self.dc.message.SetLabel("please choose contained value")
        if tpass==False:
            return
        tpass=False
        if Tclient!="":
            tpass=True
        else:
            self.dc.message.SetLabel("please select something for customer")
        if tpass==False:
            return
        tpass=True
        if Tclient=="Customer mentioned":
            if Tcontenu=="Customer Name":
                tpass=True
            else:
                self.dc.message.SetLabel("The value 'Customer name' must be selected\n in the customer choice for this function")
                tpass=False
        if tpass==False:
            return
        tpass=True
        if Tprestation=="Service mentioned":
            if Tcontenu=="Service Name":
                tpass=True
            else:
                self.dc.message.SetLabel("The value 'Service name' must be selected\n in the customer choice for this function")
                tpass=False
        if tpass==False:
            return
        try:
            chemFS= oscurdir + os.sep + "wok"+os.sep+ "conf"+os.sep+"gaors.gwh"
            isfiltre=os.path.isfile(chemFS)
            if isfiltre==True:
                logfile = open(chemFS,'rb')
            else:
                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"                
        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("filter title already used")
                return
##        print 'gorl'                    
        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, 460, 'Chronos Monitor',"Filter added")


    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=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"
                isfiltre=os.path.isfile(chemFS)
                if isfiltre==True:
                    logfile = open(chemFS,'rb')
                else:
                    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"                    
            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, 460, 'Chronos Monitor',"Filters deleted")
        except:
            self.dc.message.SetLabel("error in filter management")
                            
    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, 'Add' ,pos=(335,80) )
        self.dc.ajouter.Bind(wx.EVT_BUTTON, self.ajouteFiltre )
        self.dc.lu = wx.Button ( self.dc.paneldefinition,-1, 'Read' ,pos=(270,80), size=(30, 20))
        self.dc.lu.Bind(wx.EVT_BUTTON, self.messageLu )
        self.dc.plus = wx.Button ( self.dc.paneldefinition,-1, '+' ,pos=(300,80), size=(30, 20))
        self.dc.plus.Bind(wx.EVT_BUTTON, self.importexport )
        self.dc.si=wx.StaticText(self.dc.paneldefinition, -1, label="If :",pos=(3,8))
        self.dc.si.SetBackgroundColour('#EAEAE9')
        self.dc.alors=wx.StaticText(self.dc.paneldefinition, -1, label="Then:",pos=(3,32))
        self.dc.alors.SetBackgroundColour('#EAEAE9')
        self.dc.message = wx.StaticText(self.dc.paneldefinition, -1, message,pos=(3,79))
        self.dc.message.SetBackgroundColour('#EAEAE9')
        self.dc.libelleclient=wx.StaticText(self.dc.paneldefinition, -1, label="Customer=",pos=(40,32))
        self.dc.libelleclient.SetBackgroundColour('#EAEAE9')
        self.dc.libelleactivite=wx.StaticText(self.dc.paneldefinition, -1, label="Service=",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, 'Name:',pos=(284,32))
        self.dc.libellefiltre.SetBackgroundColour('#EAEAE9')
        contenants = ['','Window Title', 'Software Path', 'Software Name', 'File Path', 'File Name']
        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 = ['','contain', 'is equal to']
        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)
        xcontenu=['','Customer Name','Service Name']
        self.dc.contenu=wx.ComboBox(self.dc.paneldefinition, 2858, size=(185, -1),pos=(230,5), choices=xcontenu)
        self.dc.contenu.Bind(wx.EVT_COMBOBOX, self.OnContenuSelect)
        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=(116,30), choices=xlisteclient, 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=xlisteactivite, 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=str(x)
            fbox[x]=wx.CheckBox(self.dc.panelp,int(idx),label=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, 'Delete',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)

        event.Skip()


    def OnDraw(self):
        self.chargeFiltres()
        self.chargeDonnees()
        self.Draw()        
        
    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.Contains(pos):
            self.Close()
        elif self.validRegion.Contains(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.Contains(pos):
            #wx.BufferedDC(wx.ClientDC(self),self.closer)
            enter=True
        elif self.validRegion.Contains(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 AnalyseIE(wx.Frame):
    global HOST_IP,jak,dina,message,vtp,line1,line2,line3,ElChaloR,oscurdir,filtrex,Tcontenant,Tcontenu,Tpropriete,Tfiltre,Tclient,Tprestation,Tprestationid,xlisteclient,xlisteactivite,listetache,dusers,user_id,usersecretid,poste,xfiltrex,deltatrsp
    def __init__(self, parent, id, title,messagem):
        global HOST_IP,jak,dina,message,vtp,line1,line2,line3,ElChaloR,oscurdir,filtrex,Tcontenant,Tcontenu,Tpropriete,Tfiltre,Tclient,Tprestation,Tprestationid,xlisteclient,xlisteactivite,listetache,dusers,user_id,usersecretid,poste,xfiltrex,deltatrsp,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(11, wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL, 
		wx.FONTWEIGHT_BOLD, False, 'ComicSansMS')

        #self.panel=wx.Panel(self,-1)

        self.hasShape=False
        self.delta=(0,0)

        self.image_file = oscurdir+os.sep+'img'+os.sep+'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(oscurdir+os.sep+'img'+os.sep+'analyse-rollover.png', wx.BITMAP_TYPE_PNG)
        self.closer = wx.Bitmap(oscurdir+os.sep+'img'+os.sep+'analyse-close.png', wx.BITMAP_TYPE_PNG)
        self.close = wx.Bitmap(oscurdir+os.sep+'img'+os.sep+'close-normal.png', wx.BITMAP_TYPE_PNG)
        self.valida = wx.Bitmap(oscurdir+os.sep+'img'+os.sep+'analyse-appui.png', wx.BITMAP_TYPE_PNG)
        self.validr = wx.Bitmap(oscurdir+os.sep+'img'+os.sep+'analyse-rollover.png', wx.BITMAP_TYPE_PNG)
        self.valid = wx.Bitmap(oscurdir+os.sep+'img'+os.sep+'valider-normal.png', wx.BITMAP_TYPE_PNG)
        self.fond = wx.Bitmap(oscurdir+os.sep+'img'+os.sep+'analyse-fond.png', wx.BITMAP_TYPE_PNG)

        oscurdir=os.path.dirname(os.path.realpath('WIM.app'))
        filtrex={}
        xfiltrex={}
        checkfichier={}
        jak='2164691737824342'
        filtrex['nombre']=0
        xfiltrex['nombre']=0
        Tcontenant=""
        Tcontenu=""
        Tpropriete=""
        Tfiltre=""
        Tclient=""
        Tprestation=""
        Ttache=""
        Tprestationid=""
        xlisteclient = ['non défini']
        xlisteactivite = ['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="Please visit :"
        line2=str(users['serverdomain'])
        line3="To obtain activation key"  
        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.Region(self.bitmap)
        self.validRegion = wx.Region(self.valid)
        self.closeRegion = wx.Region(self.close)


        self.validRegion.Intersect(self.bitmapRegion)
        self.validRegion.Offset(316, 242)

        self.closeRegion.Intersect(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()

        self.OnDraw()

    def SetNoteShape(self, *event):
        #region=wx.RegionColour(self.bitmap,'#000000',0)
        region = wx.Region(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 filtrex
        uzer=event.GetId()
##        p=0
        hip=uzer
##        for char in str(uzer):
##            if p >2:
##                hip=hip+char
##            p+=1
        if filtrex["checked",int(hip)]==False:
            filtrex["checked",int(hip)]=True

        else:
            filtrex["checked",int(hip)]=False


        self.dc.contenanttxt.SetLabel(filtrex["Libelle",int(hip)] + ": Si "+filtrex["Contenant",int(hip)] )
        self.dc.contenutxt.SetLabel(filtrex["Propriete",int(hip)] + ' "'+  filtrex["Contenu",int(hip)]+'"' )
        self.dc.clienttxt.SetLabel("Then Customer = " + filtrex["Client",int(hip)] )
        self.dc.activitetxt.SetLabel("And Service = " + filtrex["Prestation",int(hip)] )
    def OnxFiltreCheck(self,event):
        global xsfiltrex
        uzer=event.GetId()
##        p=0
        hip=uzer
##        for char in str(uzer):
##            if p >2:
##                hip=hip+char
##            p+=1
        if xfiltrex["checked",int(hip)]==False:
            xfiltrex["checked",int(hip)]=True
        else:
            xfiltrex["checked",int(hip)]=False


        self.dc.contenanttxt.SetLabel(xfiltrex["Libelle",int(hip)] + ": Si "+xfiltrex["Contenant",int(hip)] )
        self.dc.contenutxt.SetLabel(xfiltrex["Propriete",int(hip)] + ' "'+  xfiltrex["Contenu",int(hip)]+'"' )
        self.dc.clienttxt.SetLabel("Alors Client = " + xfiltrex["Client",int(hip)] )
        self.dc.activitetxt.SetLabel("Et Prestation = " + xfiltrex["Prestation",int(hip)] )
    def chargeFiltres(self):
        global filtrex,message
        try:
            try:
                chemFS= oscurdir + os.sep + "wok"+os.sep+ "conf"+os.sep+"gaors.gwh"
                isfiltre=os.path.isfile(chemFS)
                if isfiltre==True:
                    logfile = open(chemFS,'rb')
                else:
                    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"                    
            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
            filtrex['nombre']=0
            for unam in unem:
                filtrex['Libelle',x]=unam.getAttribute('Libelle')
                filtrex['nombre']=x
                filtrex['Contenant',x]=unam.getAttribute('Contenant')
                filtrex['Propriete',x]=unam.getAttribute('Propriete')
                filtrex['Contenu',x]=unam.getAttribute('Contenu')
                filtrex['Client',x]=unam.getAttribute('Client')
                filtrex['Prestation',x]=unam.getAttribute('Prestation')
                filtrex['Prestationid',x]=unam.getAttribute('Prestationid')
                filtrex["checked",x]=True
                x+=1
        except:
            message="error during filters loading"
                
    def chargeDonnees(self):
        global listeclient,listeactivite,message,poste,presta,dusers,user_id,usersecretid,xfiltrex,users,HOST_IP
        try:
            TchemFSF=oscurdir+os.sep+'wok'+os.sep+'conf'+os.sep+'local.gwh'
            isconfig=os.path.isfile(TchemFSF)
            if isconfig==True:
                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
                ip_enter=False
                go_on=True
                for char in lines:
                    if char=='\t':
                        p+=1
                        continue
                    if char=='\n':
                        break
                    if p==0 and l==0 and char in ['i','p',':']:
                        ip_enter=True
                        go_on=False
                        continue
                    if go_on==False:
                        if ip_enter==True and p==0 and l==0:
                            users['serverip']=users['serverip']+char
                        if p==1 and l==0:users['serverdomain']+char
                        if p==2 and l==0:poste["PID"]=poste["PID"]+char
                        if p==3 and l==0:poste["ID"]=poste["ID"]+char
                        if p==4 and l==0:poste["posteNAME"]=poste["posteNAME"]+char
                        if p==5 and l==0:poste["Date"]=poste["Date"]+char
                        if p==6 and l==0:poste["GUID"]=poste["GUID"]+char
                        if p==7 and l==0:poste["ADMINID"]=poste["ADMINID"]+char
                    else:
                        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
                        users['serverip']='88.191.122.246'
                        users['serverdomain']='http://www.chronosmonitor.com' 
                if poste["ADMINID"]!="":
                    if dusers['sfiltre']=='1':
                        usersecretid=user_id
                    else:
                        usersecretid=0
##                    print 'userid '+str(usersecretid)
##                    print 'adminid '+str(poste["ADMINID"])
                    conn_string = "host='"+str(HOST_IP)+"' dbname='chronos-monitor.com' user='chronos' password='gortex855'"
                    conn = psycopg2.connect(conn_string)
                    conn.set_client_encoding('UTF8')
                    curs = conn.cursor()
                    result=curs.execute("SELECT libelle, contenant, contenu, propriete,client, prestation, prestationid FROM filtres WHERE secret='0' AND adminid='"+str(poste["ADMINID"])+"';" )
                    rresult=curs.fetchall()
                    if rresult:
                        x=1
                        for rchain in rresult:
                            p=0
                            xfiltrex['Libelle',x]=""
                            xfiltrex['nombre']=x
                            xfiltrex['Contenant',x]=""
                            xfiltrex['Propriete',x]=""
                            xfiltrex['Contenu',x]=""
                            xfiltrex['Client',x]=""
                            xfiltrex['Prestation',x]=""
                            xfiltrex['Prestationid',x]=""
                            xfiltrex["checked",x]=True
                            for rrchar in rchain:
                                if p==0:xfiltrex['Libelle',x]=xfiltrex['Libelle',x]+str(rrchar).decode('utf-8')
                                if p==1:xfiltrex['Contenant',x]=xfiltrex['Contenant',x]+str(rrchar).decode('utf-8')
                                if p==2:xfiltrex['Contenu',x]=xfiltrex['Contenu',x]+str(rrchar).decode('utf-8')
                                if p==3:xfiltrex['Propriete',x]=xfiltrex['Propriete',x]+str(rrchar).decode('utf-8')
                                if p==4:xfiltrex['Client',x]=xfiltrex['Client',x]+str(rrchar).decode('utf-8')
                                if p==5:xfiltrex['Prestation',x]=xfiltrex['Prestation',x]+str(rrchar).decode('utf-8')
                                if p==6:xfiltrex['Prestationid',x]=xfiltrex['Prestationid',x]+str(rrchar).decode('utf-8')
                                p+=1
                            x+=1
                    if usersecretid!=0:
                        result=curs.execute("SELECT libelle, contenant, contenu, propriete,client, prestation, prestationid FROM filtres WHERE secret='"+usersecretid+"' AND adminid='"+str(poste["ADMINID"])+"';" )
                        rresult=curs.fetchall()
                        if rresult:
                            for rchain in rresult:
                                #print chain
                                p=0
                                xfiltrex['Libelle',x]=""
                                xfiltrex['nombre']=x
                                xfiltrex['Contenant',x]=""
                                xfiltrex['Propriete',x]=""
                                xfiltrex['Contenu',x]=""
                                xfiltrex['Client',x]=""
                                xfiltrex['Prestation',x]=""
                                xfiltrex['Prestationid',x]=""
                                xfiltrex["checked",x]=True
                                for rrchar in rchain:
                                    if p==0:xfiltrex['Libelle',x]=xfiltrex['Libelle',x]+str(rrchar)
                                    if p==1:xfiltrex['Contenant',x]=xfiltrex['Contenant',x]+str(rrchar)
                                    if p==2:xfiltrex['Contenu',x]=xfiltrex['Contenu',x]+str(rrchar)
                                    if p==3:xfiltrex['Propriete',x]=xfiltrex['Propriete',x]+str(rrchar)
                                    if p==4:xfiltrex['Client',x]=xfiltrex['Client',x]+str(rrchar)
                                    if p==5:xfiltrex['Prestation',x]=xfiltrex['Prestation',x]+str(rrchar)
                                    if p==6:xfiltrex['Prestationid',x]=xfiltrex['Prestationid',x]+str(rrchar)
                                    p+=1
                                x+=1                    
                    result=curs.execute("SELECT nomsoc FROM clients WHERE idadmin='"+str(poste["ADMINID"])+"';" )
                    result=curs.fetchall()
                    xlisteclient.append('Customer mentioned')
                    if result:
                        for chain in result:
                            Tclient=""
                            for char in chain:
                                Tclient=Tclient+str(char)
                            xlisteclient.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
                    xlisteactivite.append('Service mentioned')
                    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
                            xlisteactivite.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
                                    xlisteactivite.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
                                            xlisteactivite.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="error : run configuration wizard before"
            else:
                message="error : run configuration wizard before"
        except:
            message="Internet connection required"
        

    def importFiltre(self,event):
        global message,xfiltrex
        try:
            chemFS= oscurdir + os.sep + "wok"+os.sep+ "conf"+os.sep+"gaors.gwh"
            isfiltre=os.path.isfile(chemFS)
            if isfiltre==True:
                logfile = open(chemFS,'rb')
            else:
                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"                
        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("Filter title already in use")
                return                   
        racine=xim.documentElement
        for x in range(1,int(xfiltrex['nombre'])+1):
            if xfiltrex["checked",x]==True:
                element =xim.createElement("FILTRE")
                element.setAttribute("Libelle",xfiltrex["Libelle",x])
                element.setAttribute("Contenant",xfiltrex["Contenant",x])
                element.setAttribute("Propriete",xfiltrex["Propriete",x])
                element.setAttribute("Contenu",xfiltrex["Contenu",x])
                element.setAttribute("Client",xfiltrex["Client",x])
                element.setAttribute("Prestation",xfiltrex["Prestation",x])
                element.setAttribute("Prestationid",xfiltrex["Prestationid",x])
                racine.appendChild(element)

        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()
        try:
            frame=wx.FindWindowById(460)
            if frame.IsShown():
                frame.Close()
        except:
            pass
        Analyse(None, 460, 'Chronos Monitor Analyse',"Filters imported")
        AnalyseIE(None, 472, 'Chronos Monitor Import Export Filtres',"Filters imported")


    def ajouteFiltres(self):
        global filtrex,xfbox
        #self.dc.postboxp.Clear(True)
        for x in range(1,int(filtre['nombre'])+1):
            #print x
            posy=(int(x)*10)
            idx=str(x)
            xfbox[x]=wx.CheckBox(self.dc.panelp,int(idx),label=str(filtrex['Libelle',int(x)]))
            self.dc.postboxp.Add(fbox[x],wx.LEFT)
            xfbox[x].Bind(wx.EVT_CHECKBOX, self.OnFiltreCheck)
        #self.dc.postboxp.ShowItems(True)
    
    def exportFiltre(self,event):
        global filtrex,poste,dusers,user_id,usersecretid,users,HOST_IP
##        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
        conn_string = "host='"+str(HOST_IP)+"' dbname='chronos-monitor.com' user='chronos' password='gortex855'"
        conn = psycopg2.connect(conn_string)
        conn.set_client_encoding('UTF8')
        curs = conn.cursor()
        for x in range(1,int(filtrex['nombre'])+1):
            if filtrex["checked",x]==True:
                #print 'prestationid '+str(filtrex['Prestationid',x])
                if str(filtrex['Prestationid',x])=="":
                    filtrex['Prestationid',x]=0
                strin="""INSERT INTO filtres (libelle, contenant, contenu, propriete,client, prestation, prestationid, secret, adminid) VALUES """
                result=curs.execute("SELECT * FROM filtres WHERE libelle='"+filtrex['Libelle',x]+"' AND contenant='"+filtrex['Contenant',x]+"' AND contenu='"+filtrex['Contenu',x]+"' AND propriete='"+filtrex['Propriete',x]+"' AND client='"+filtrex['Client',x]+"' AND prestationid='"+str(filtrex['Prestationid',x])+"' AND adminid='"+str(poste['ADMINID'])+"' AND secret='"+str(usersecretid)+"';" )
                rresult=curs.fetchall()
                
                if rresult:
                    pass
                else:
                    strin=strin+"('"+filtrex['Libelle',x]+"','"+filtrex['Contenant',x]+"','"+filtrex['Contenu',x]+"','"+filtrex['Propriete',x]+"','"+filtrex['Client',x]+"','"+filtrex['Prestation',x]+"','"+str(filtrex['Prestationid',x])+"','"+str(usersecretid)+"','"+str(poste['ADMINID'])+"');"                                                                                                              

                    try:
                        result=curs.execute(strin)
                        conn.commit()
##                        print strin
                    except:
                        pass
                        #exceptionType, exceptionValue, exceptionTraceback = sys.exc_info()
                        #print "Database connection failed!\n ->%s" % (exceptionValue)

##                    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()
        AnalyseIE(None, 472, 'Chronos Monitor Import Export Filtres',"Filters exported")
##        except:
##            self.dc.message.SetLabel("Veuillez vous connecter à internet pour exporter vos 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 filtrex,listeclient,listeactivite,xfbox,message,xfiltrex
        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.DrawText("Home filters :",10,140)
        self.dc.DrawText("OnLine filters :",170,140)
        self.dc.panel = wx.Panel ( self,-1,(10,30),(420,110), 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.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.panel, -1, 'Read' ,pos=(380,80), size=(30, 20))
        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.panel, -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)
##        xcontenu=['Le nom du client','Le nom de la prestation']
##        self.dc.contenu=wx.ComboBox(self.dc.paneldefinition, 2858, size=(185, -1),pos=(230,5), choices=xcontenu)
##        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=xlisteclient, 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=xlisteactivite, 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,155),(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)
        xfbox={}
        for x in range(1,int(filtrex['nombre'])+1):
            #print x
            posy=(int(x)*10)
            idx=str(x)
            xfbox[x]=wx.CheckBox(self.dc.panelp,int(idx),label=filtrex['Libelle',int(x)])
            self.dc.postboxp.Add(xfbox[x],wx.LEFT)
            xfbox[x].Bind(wx.EVT_CHECKBOX, self.OnFiltreCheck)
            xfbox[x].SetValue(True)
        self.dc.export = wx.Button ( self, 100, 'Export',pos=(160,248) ,size=(60,24))
        self.dc.export.Bind(wx.EVT_BUTTON, self.exportFiltre )
        self.dc.eimport = wx.Button ( self, 100, 'Import',pos=(235,248),size=(60,24) )
        self.dc.eimport.Bind(wx.EVT_BUTTON, self.importFiltre )
        self.dc.panelp.SetSizer(self.dc.postboxp)
        self.dc.postboxp.FitInside(self.dc.panelp)
        #=================Panel Affichage du Filtre==========================================
        self.dc.panelei = scrolled.ScrolledPanel ( self,-1,(170,155),(260,90), style=wx.SUNKEN_BORDER)
        self.dc.panelei.SetBackgroundColour('#EAEAE9')
        self.dc.panelei.SetupScrolling(scroll_x=True,scroll_y=True)
        self.dc.DrawBitmap(self.fond, 10, 300, True)
        self.dc.epostboxp=wx.BoxSizer(wx.VERTICAL)
        exfbox={}
        for x in range(1,int(xfiltrex['nombre'])+1):
            #print x
            posy=(int(x)*10)
            idx=str(x)
            exfbox[x]=wx.CheckBox(self.dc.panelei,int(idx),label=xfiltrex['Libelle',int(x)])
            self.dc.epostboxp.Add(exfbox[x],wx.LEFT)
            exfbox[x].Bind(wx.EVT_CHECKBOX, self.OnxFiltreCheck)
            exfbox[x].SetValue(True)
        self.dc.panelei.SetSizer(self.dc.epostboxp)
        self.dc.epostboxp.FitInside(self.dc.panelei)
##        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)

        event.Skip()

    def OnDraw(self):
        self.chargeFiltres()
        self.chargeDonnees()
        self.Draw()        

        
    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.Contains(pos):
            self.Close()
        elif self.validRegion.Contains(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.Contains(pos):
            #wx.BufferedDC(wx.ClientDC(self),self.closer)
            enter=True
        elif self.validRegion.Contains(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 slogpath,reset,jak,dina,message,vtp,line1,line2,line3,ElChaloR,oscurdir,encfile,checkfichier,deltatrsp
    def __init__(self, parent, id, title):
        global slogpath,reset,jak,dina,message,vtp,line1,line2,line3,ElChaloR,oscurdir,encfile,checkfichier,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, 'ComicSansMS')

        #self.panel=wx.Panel(self,-1)

        self.hasShape=False
        self.delta=(0,0)


        self.image_file = oscurdir+os.sep+'img'+os.sep+'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(oscurdir+os.sep+'img'+os.sep+'dossier-appui.png', wx.BITMAP_TYPE_PNG)
        self.closer = wx.Bitmap(oscurdir+os.sep+'img'+os.sep+'export-close.png', wx.BITMAP_TYPE_PNG)
        self.close = wx.Bitmap(oscurdir+os.sep+'img'+os.sep+'close-normal.png', wx.BITMAP_TYPE_PNG)
        self.valida = wx.Bitmap(oscurdir+os.sep+'img'+os.sep+'dossier-appui.png', wx.BITMAP_TYPE_PNG)
        self.validr = wx.Bitmap(oscurdir+os.sep+'img'+os.sep+'export-rollover.png', wx.BITMAP_TYPE_PNG)
        self.valid = wx.Bitmap(oscurdir+os.sep+'img'+os.sep+'valider-normal.png', wx.BITMAP_TYPE_PNG)
        self.fond = wx.Bitmap(oscurdir+os.sep+'img'+os.sep+'wizard-fond.png', wx.BITMAP_TYPE_PNG)

        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="Please visit :"
        line2="http://www.chronosmonitor.fr"
        line3="To obtain an activation key"  
        enter=False         
        self.SetTransparent(int(deltatrsp))
        self.chargeFichiers()
        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.Region(self.bitmap)
        self.validRegion = wx.Region(self.valid)
        self.closeRegion = wx.Region(self.close)


        self.validRegion.Intersect(self.bitmapRegion)
        self.validRegion.Offset(316, 242)

        self.closeRegion.Intersect(self.bitmapRegion)
        self.closeRegion.Offset(408, 12)
      
        self.dc=wx.BufferedDC(wx.ClientDC(self),self.bitmap)
        #self.dc = wx.ClientDC(self)
##        self.dc.DrawBitmap(self.bitmap, 0, 0, True)
        self.Show(True)
#        self.Fit()
        self.Centre()
        self.OnDraw()



    def SetNoteShape(self, *event):
        #region=wx.RegionColour(self.bitmap,'#000000',0)
        region = wx.Region(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("Choose files to export :",10,30)

    def chargeFichiers(self):
        global encfile,slogpath
        x=1
        encdir=slogpath
        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,slogpath,oscurdir
        try:
            message="error during export"
            encdir=slogpath
            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=oscurdir+os.sep+'export'+os.sep+fic[0:kp-4]+'.csv'
                            
                            logfile = open(chemt, mode ='w')
                            def MTWrite(data):
                                logfile.write(data.encode('iso-8859-1'))
                            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()
            message="The files has been exported in the export folder"
            self.dc.message.SetLabel(message)
        except:
            message="Error Somewhere"
            self.dc.message.SetLabel(message)
            
        


 
    def Lu(self,event):
        self.dc.message.SetLabel('')




    
    def Draw(self):
        global encfile
        #self.dc = wx.ClientDC(self)
        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("Choose files to export :",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, 'Read',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.dc = wx.ClientDC(self)
##        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("Choose files to export :",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, 'Read',pos=(100,30) )
##        self.dc.lu.Bind(wx.EVT_BUTTON, self.Lu )
##        self.chargeFichiers()
##        self.Draw()
#        self.DShow()
        event.Skip()


    def OnDraw(self):
        #wx.BufferedPaintDC(self,self.bitmap)
        #self.chargeFichiers()
        self.Draw()
        #pass
        
    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.Contains(pos):
            self.Close()
        elif self.validRegion.Contains(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.Contains(pos):
            #wx.BufferedDC(wx.ClientDC(self),self.closer)
            #self.DShow()
            enter=True
        elif self.validRegion.Contains(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,deltatrsp
    def __init__(self, parent, id, title):
        global reset,jak,dina,message,vtp,line1,line2,line3,ElChaloR,oscurdir,dossier,undossier,explorer,path,logfull,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, 'ComicSansMS')

        #self.panel=wx.Panel(self,-1)

        self.hasShape=False
        self.delta=(0,0)

        self.image_file = oscurdir+os.sep+'img'+os.sep+'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(oscurdir+os.sep+'img'+os.sep+'dossier-appui.png', wx.BITMAP_TYPE_PNG)
        self.closer = wx.Bitmap(oscurdir+os.sep+'img'+os.sep+'dossier-close.png', wx.BITMAP_TYPE_PNG)
        self.close = wx.Bitmap(oscurdir+os.sep+'img'+os.sep+'close-normal.png', wx.BITMAP_TYPE_PNG)
        self.valida = wx.Bitmap(oscurdir+os.sep+'img'+os.sep+'dossier-appui.png', wx.BITMAP_TYPE_PNG)
        self.validr = wx.Bitmap(oscurdir+os.sep+'img'+os.sep+'dossier-rollover.png', wx.BITMAP_TYPE_PNG)
        self.valid = wx.Bitmap(oscurdir+os.sep+'img'+os.sep+'valider-normal.png', wx.BITMAP_TYPE_PNG)
        self.fond = wx.Bitmap(oscurdir+os.sep+'img'+os.sep+'wizard-fond.png', wx.BITMAP_TYPE_PNG)

        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="Please visit :"
        line2="http://www.chronosmonitor.fr"
        line3="To obtain activation key"  
        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.Region(self.bitmap)
        self.validRegion = wx.Region(self.valid)
        self.closeRegion = wx.Region(self.close)


        self.validRegion.Intersect(self.bitmapRegion)
        self.validRegion.Offset(316, 242)

        self.closeRegion.Intersect(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 dossiers a superviser'

        self.OnDraw()

    def SetNoteShape(self, *event):
        #region=wx.RegionColour(self.bitmap,'#000000',0)
        region = wx.Region(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"
            isdos=os.path.isfile(chemFS)
            if isdos==True:
                logfile = open(chemFS,'rb')
            else:
                chemFS= oscurdir + os.sep + "wok"+os.sep+ "need"+os.sep+"zero.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
##            print dossier['path',x]
            x+=1
  
    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,
##          "Choose a folder",
##          0,
##          None,
##          None
##        )
##        if shell.SHGetPathFromIDList (pidl)=="":
##          mes.set(u"no folder choose")
##          return
##        else:path=shell.SHGetPathFromIDList (pidl)
        
##        try:
        openFileDialog = wx.DirDialog(None, "Choose a directory:",style=wx.DD_DEFAULT_STYLE | wx.DD_NEW_DIR_BUTTON)
        #if openFileDialog.ShowModal() == wx.ID_CANCEL:
            #return
        if openFileDialog.ShowModal() == wx.ID_OK:
            path=openFileDialog.GetPath()
        openFileDialog.Destroy()        
        #self.dc.bakpath.SetValue(path)
        try:
            chemFS= oscurdir + os.sep + "wok"+os.sep+ "conf"+os.sep+"resap.gwh"
            isdos=os.path.isfile(chemFS)
            if isdos==True:                
                logfile = open(chemFS,'rb')
                zero=False
            else:
                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                
        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)
 

        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 dirDelete(self,event):
        global undossier
        #try:
        try:
            chemFS= oscurdir + os.sep + "wok"+os.sep+ "conf"+os.sep+"resap.gwh"
            isdos=os.path.isfile(chemFS)
            if isdos==True:
                logfile = open(chemFS,'rb')
            else:
                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"                
        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
        openFileDialog = wx.FileDialog(self, "Open XYZ file", "", "",
                                       "XYZ files (*.xyz)|*.xyz", wx.FD_OPEN | wx.FD_FILE_MUST_EXIST)
        if openFileDialog.ShowModal() == wx.ID_CANCEL:
            return
        path=wx.FileInputStream(openFileDialog.GetPath())
        
        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("Choose the folders to monitor :",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("Choose the folders to monitor :",10,30)
        self.dc.panelp=scrolled.ScrolledPanel(self,-1,(10,50),(400,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, 'New Folder' )
        self.dc.newdir.Bind(wx.EVT_BUTTON, self.newDir )
        self.dc.nodir = wx.Button ( self.dc.panel, 100, 'Withdraw Folder' )
        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.Show ( True )
        #print '1'
        
    def OnPaint(self, event):
        #global postes,users,dc,box,panelp

        wx.BufferedPaintDC(self,self.bitmap)
        self.DShow()
        #self.Draw()
        event.Skip()

    def OnDraw(self):
        #wx.BufferedPaintDC(self,self.bitmap)
        #wx.BufferedDC(wx.ClientDC(self),self.bitmap)
        self.chargeDossier()
        self.Draw()
        

    def saveConfig(self):
        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.Contains(pos):
            self.Close()
        elif self.validRegion.Contains(pos):
            wx.BufferedDC(wx.ClientDC(self),self.valida)
            try:
                self.saveConfig()
                try:
                        reset=True
                        line1="Configuration registered."
                        line2="Relaunch the program"
                        line3="to take into account"
                        self.Close()
                        try:
                            dialogframe = wx.FindWindowById(465)
                            dialogframe.Close()
                            WizardEnd(None, 465, 'Chronos Monitor Dossiers')            
                        except:
                            WizardEnd(None, 465, 'Chronos Monitor Dossiers')
                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.Contains(pos):
            #wx.BufferedDC(wx.ClientDC(self),self.closer)
            #self.DShow()
            enter=True
        elif self.validRegion.Contains(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,deltatrsp,oscurdir
    def __init__(self, parent, id, title):
        global enter,dusers,line1,line2,line3,deltatrsp,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, 'ComicSansMS')

        #self.panel=wx.Panel(self,-1)

        self.hasShape=False
        self.delta=(0,0)

        self.image_file = oscurdir+os.sep+'img'+os.sep+'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(oscurdir+os.sep+'img'+os.sep+'option_0.png', wx.BITMAP_TYPE_PNG)
        self.wizard = wx.Bitmap(oscurdir+os.sep+'img'+os.sep+'wizard-normal.png', wx.BITMAP_TYPE_PNG)
        self.wizarda = wx.Bitmap(oscurdir+os.sep+'img'+os.sep+'option_ass_appui.png', wx.BITMAP_TYPE_PNG)
        self.wizardr = wx.Bitmap(oscurdir+os.sep+'img'+os.sep+'option_ass_rollover.png', wx.BITMAP_TYPE_PNG)
        self.usersa = wx.Bitmap(oscurdir+os.sep+'img'+os.sep+'option_ge_appui.png', wx.BITMAP_TYPE_PNG)
        self.usersr = wx.Bitmap(oscurdir+os.sep+'img'+os.sep+'option_ge_rollover.png', wx.BITMAP_TYPE_PNG)
        self.dossiersa = wx.Bitmap(oscurdir+os.sep+'img'+os.sep+'option_su_appui.png', wx.BITMAP_TYPE_PNG)
        self.dossiersr = wx.Bitmap(oscurdir+os.sep+'img'+os.sep+'option_su_rollover.png', wx.BITMAP_TYPE_PNG)
        self.closer = wx.Bitmap(oscurdir+os.sep+'img'+os.sep+'option_close_rollover.png', wx.BITMAP_TYPE_PNG)
        self.analysea = wx.Bitmap(oscurdir+os.sep+'img'+os.sep+'option_an_appui.png', wx.BITMAP_TYPE_PNG)
        self.analyser = wx.Bitmap(oscurdir+os.sep+'img'+os.sep+'option_an_rollover.png', wx.BITMAP_TYPE_PNG)
        self.parama = wx.Bitmap(oscurdir+os.sep+'img'+os.sep+'option_para_appui.png', wx.BITMAP_TYPE_PNG)
        self.paramr = wx.Bitmap(oscurdir+os.sep+'img'+os.sep+'option_para_rollover.png', wx.BITMAP_TYPE_PNG)
        self.wizard = wx.Bitmap(oscurdir+os.sep+'img'+os.sep+'wizard-normal.png', wx.BITMAP_TYPE_PNG)
        self.users = wx.Bitmap(oscurdir+os.sep+'img'+os.sep+'users-normal.png', wx.BITMAP_TYPE_PNG)
        self.dossiers = wx.Bitmap(oscurdir+os.sep+'img'+os.sep+'dossiers-normal.png', wx.BITMAP_TYPE_PNG)
        self.close = wx.Bitmap(oscurdir+os.sep+'img'+os.sep+'close-normal.png', wx.BITMAP_TYPE_PNG)
        self.analyse = wx.Bitmap(oscurdir+os.sep+'img'+os.sep+'dossiers-normal.png', wx.BITMAP_TYPE_PNG)
        self.param = wx.Bitmap(oscurdir+os.sep+'img'+os.sep+'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()))


##        line1="options login"
##        line2="no special" 
##        line3="nothing else"
##        try:
##            dialogframe = wx.FindWindowById(465)
##            dialogframe.Close()
##            WizardEnd(None, 465, 'Chronos Monitor Configuration')            
##        except:
##            WizardEnd(None, 465, 'Chronos Monitor Configuration')

        if wx.Platform == '__WXGTK__':
            self.Bind(wx.EVT_WINDOW_CREATE, self.SetNoteShape)
        else: self.SetNoteShape()


        enter=False         
        #MyButton(self.panel,-1,(47,168),oscurdir+os.sep+'img'+os.sep+'sync-normal.png',oscurdir+os.sep+'img'+os.sep+'sync-rollover.png',oscurdir+os.sep+'img'+os.sep+'appui-sync.png')
        #self.SetTransparent(220)
        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.Region(self.bitmap)
        self.wizardRegion = wx.Region(self.wizard)
        self.usersRegion = wx.Region(self.users)
        self.dossiersRegion = wx.Region(self.dossiers)
        self.closeRegion = wx.Region(self.close)
        self.analyseRegion = wx.Region(self.analyse)
        self.paramRegion = wx.Region(self.param)


        self.wizardRegion.Intersect(self.bitmapRegion)
        self.wizardRegion.Offset(22, 60)

        self.usersRegion.Intersect(self.bitmapRegion)
        self.usersRegion.Offset(22, 92)

        self.dossiersRegion.Intersect(self.bitmapRegion)
        self.dossiersRegion.Offset(22, 130)  

        self.closeRegion.Intersect(self.bitmapRegion)
        self.closeRegion.Offset(201, 12)

        self.analyseRegion.Intersect(self.bitmapRegion)
        self.analyseRegion.Offset(22, 170)

        self.paramRegion.Intersect(self.bitmapRegion)
        self.paramRegion.Offset(117, 252)        
      
#        self.dc=wx.BufferedDC(wx.ClientDC(self),self.bmp)
        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),oscurdir+os.sep+'img'+os.sep+'sync-normal.png',oscurdir+os.sep+'img'+os.sep+'sync-rollover.png',oscurdir+os.sep+'img'+os.sep+'appui-sync.png')

        self.OnDraw()


    def BringWindowToFront(self):
        try: # it's possible for this event to come when the frame is closed
            self.GetTopWindow().Raise()
        except:
            pass
        
    def OnActivate(self, event):
        # if this is an activate event, rather than something else, like iconize.
        if event.GetActive():
            self.BringWindowToFront()
        event.Skip()

    def OnClose(self, event):
        #self.tskic.Destroy()
        self.Destroy()


    def SetNoteShape(self, *event):
        #region=wx.RegionColour(self.bitmap,'#000000',0)
        region = wx.Region(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()
        event.Skip()

        
    def OnDraw(self):
        #wx.BufferedPaintDC(self,self.bitmap)
        wx.BufferedDC(wx.ClientDC(self),self.bitmap)
        self.Draw()
        #self.BringWindowToFront()




    def OnLeftDown(self, event):
        global line1,line2,line3,dusers
        pos = event.GetPosition()
        if self.closeRegion.Contains(pos):
            self.Close()
        elif self.wizardRegion.Contains(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 not authorized"
                line2="ask the authorization" 
                line3="to your administrator"
                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.Contains(pos):
            wx.BufferedDC(wx.ClientDC(self),self.usersa)
            if dusers['active']==False:
                line1="Please"
                line2="make the wizard first" 
                line3="to configure your work station"
                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 not authorized"
                line2="ask the authorization" 
                line3="to your administrator"
                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.Contains(pos):
            wx.BufferedDC(wx.ClientDC(self),self.dossiersa)
            if dusers['active']==False:
                line1="Please"
                line2="make the wizard first" 
                line3="to configure your work station"
                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 not authorized"
                line2="ask the authorization" 
                line3="to your administrator"
                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.Contains(pos):
            wx.BufferedDC(wx.ClientDC(self),self.analysea)
            if dusers['active']==False:
                line1="Please"
                line2="make the wizard first" 
                line3="to configure your work station"
                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 not authorized"
                line2="ask the authorization" 
                line3="to your administrator"
                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',"Build your filters")
        elif self.paramRegion.Contains(pos):
            wx.BufferedDC(wx.ClientDC(self),self.parama)
            if dusers['active']==False:
                line1="Please"
                line2="make the wizard first" 
                line3="to configure your work station"
                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 not authorized"
                line2="ask the authorization" 
                line3="to your administrator"
                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.Contains(pos):
                wx.BufferedDC(wx.ClientDC(self),self.closer)
                enter=True
            elif self.wizardRegion.Contains(pos):
                wx.BufferedDC(wx.ClientDC(self),self.wizardr)
                enter=True
            elif self.usersRegion.Contains(pos):
                wx.BufferedDC(wx.ClientDC(self),self.usersr) 
                enter=True
            elif self.dossiersRegion.Contains(pos):
                wx.BufferedDC(wx.ClientDC(self),self.dossiersr)
                enter=True
            elif self.analyseRegion.Contains(pos):
                wx.BufferedDC(wx.ClientDC(self),self.analyser)
                enter=True
            elif self.paramRegion.Contains(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 zname,zaction,zeventname,zowner,owner,name,observer,stream,cocoastart,encodings,on_open,invisible,hmh,fcl,dina,slogpath,issyncro,tenter,line1,line2,line3,dusers,explorer,fanal,poste_pid,dossier,reset,ssyncro,deltatrsp,to,fl,cl,jak,filtre,anaprocspathin,anaprocspatheq,anaprocsnamin,anaprocsnameq,anaficpathin,anaficpatheq,anaficnamin,anaficnameq,anafennamin,anafennameq,obj,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,watcher,user_id,users

    def __init__(self, parent, id, title):
        global zname,zaction,zeventname,zowner,owner,name,observer,stream,cocoastart,encodings,on_open,invisible,hmh,conex,cursex,connec,lffile,lcfile,fline,cline,fcl,dina,ffile,cfile,sconauto,slogrep,slogpath,Tuser,sviewer,issyncro,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,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,watcher,listeclient,listeactivite,user_id,users

        if invisible==False:
            wx.Frame.__init__(self, parent, id, title, size=(220, 300),style=wx.FRAME_SHAPED |wx.FRAME_NO_TASKBAR|wx.NO_BORDER|wx.FULL_REPAINT_ON_RESIZE)
        else:
            wx.Frame.__init__(self, parent, id, title, size=(220, 300),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, 'ComicSansMS')

        #self.panel=wx.Panel(self,-1)

        self.hasShape=False
        self.delta=(0,0)

        #oscurdir2=os.path.realpath(sys.frozen)
        #print ('2'+oscurdir2)
        #oscurdir3=os.path.realpath('WIM.app')
        #print ('3'+oscurdir3)
        #oscurdir=oscurdir3
        self.bitmap = wx.Bitmap(oscurdir+os.sep+'img'+os.sep+'window.gif', wx.BITMAP_TYPE_GIF)
        if invisible==False:
            self.image_file = oscurdir+os.sep+'img'+os.sep+'window.png'
            self.bmp = wx.Bitmap(self.image_file)
            #bg=wx.StaticBitmap(self.panel, wx.ID_ANY, bmp, (0, 0)), size=(220, 300)
            
            
            self.cross = wx.Bitmap(oscurdir+os.sep+'img'+os.sep+'close-normal.png', wx.BITMAP_TYPE_PNG)
            self.crossover = wx.Bitmap(oscurdir+os.sep+'img'+os.sep+'fermer-rollover.png', wx.BITMAP_TYPE_PNG)
            self.reduce = wx.Bitmap(oscurdir+os.sep+'img'+os.sep+'close-normal.png', wx.BITMAP_TYPE_PNG)
            self.reduceover = wx.Bitmap(oscurdir+os.sep+'img'+os.sep+'minimize-rollover.png', wx.BITMAP_TYPE_PNG)
            self.syncr = wx.Bitmap(oscurdir+os.sep+'img'+os.sep+'sync-normal2.png', wx.BITMAP_TYPE_PNG)
            self.sync = wx.Bitmap(oscurdir+os.sep+'img'+os.sep+'sync.png', wx.BITMAP_TYPE_PNG)
            self.oversync = wx.Bitmap(oscurdir+os.sep+'img'+os.sep+'sync-rollover.png', wx.BITMAP_TYPE_PNG)
            self.onsync = wx.Bitmap(oscurdir+os.sep+'img'+os.sep+'sync-appui.png', wx.BITMAP_TYPE_PNG)
            self.loginr = wx.Bitmap(oscurdir+os.sep+'img'+os.sep+'login-normal.png', wx.BITMAP_TYPE_PNG)
            self.login = wx.Bitmap(oscurdir+os.sep+'img'+os.sep+'login.png', wx.BITMAP_TYPE_PNG)
            self.overlogin = wx.Bitmap(oscurdir+os.sep+'img'+os.sep+'login-rollover.png', wx.BITMAP_TYPE_PNG)
            self.onlogin = wx.Bitmap(oscurdir+os.sep+'img'+os.sep+'login-appui.png', wx.BITMAP_TYPE_PNG)
            self.logoutr = wx.Bitmap(oscurdir+os.sep+'img'+os.sep+'logout-normal.png', wx.BITMAP_TYPE_PNG)
            self.logout = wx.Bitmap(oscurdir+os.sep+'img'+os.sep+'logout.png', wx.BITMAP_TYPE_PNG)
            self.overlogout = wx.Bitmap(oscurdir+os.sep+'img'+os.sep+'logout-rollover.png', wx.BITMAP_TYPE_PNG)
            self.onlogout = wx.Bitmap(oscurdir+os.sep+'img'+os.sep+'logout-appui.png', wx.BITMAP_TYPE_PNG)
            self.options = wx.Bitmap(oscurdir+os.sep+'img'+os.sep+'options-normal.png', wx.BITMAP_TYPE_PNG)
            self.overoptions = wx.Bitmap(oscurdir+os.sep+'img'+os.sep+'options-rollover.png', wx.BITMAP_TYPE_PNG)
            self.onoptions = wx.Bitmap(oscurdir+os.sep+'img'+os.sep+'options-appui.png', wx.BITMAP_TYPE_PNG)
            self.liste = wx.Bitmap(oscurdir+os.sep+'img'+os.sep+'liste-normal.png', wx.BITMAP_TYPE_PNG)
            self.overliste = wx.Bitmap(oscurdir+os.sep+'img'+os.sep+'liste-rollover.png', wx.BITMAP_TYPE_PNG)
            self.onliste = wx.Bitmap(oscurdir+os.sep+'img'+os.sep+'liste-appui.png', wx.BITMAP_TYPE_PNG)
            #image_file = oscurdir+os.sep+'img'+os.sep+'fond.png'
    ##        self.crossf = wx.Bitmap(oscurdir+os.sep+'img'+os.sep+'close-fond.png', wx.BITMAP_TYPE_PNG)
    ##        self.syncf = wx.Bitmap(oscurdir+os.sep+'img'+os.sep+'sync-fond.png', wx.BITMAP_TYPE_PNG)
    ##        self.loginf = wx.Bitmap(oscurdir+os.sep+'img'+os.sep+'login-fond.png', wx.BITMAP_TYPE_PNG)
    ##        self.listef = wx.Bitmap(oscurdir+os.sep+'img'+os.sep+'liste-fond.png', wx.BITMAP_TYPE_PNG)
    ##        self.logoutf = wx.Bitmap(oscurdir+os.sep+'img'+os.sep+'logout-fond.png', wx.BITMAP_TYPE_PNG)
    ##        self.reducef = wx.Bitmap(oscurdir+os.sep+'img'+os.sep+'minimize-fond.png', wx.BITMAP_TYPE_PNG)
    ##        self.optionsf = wx.Bitmap(oscurdir+os.sep+'img'+os.sep+'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 invisible==False:
        if wx.Platform == '__WXGTK__':
            self.Bind(wx.EVT_WINDOW_CREATE, self.SetNoteShape)
        else: self.SetNoteShape()



  

        pprocess={}
        pr=0
        mes=""
        dusers={}
        dusers['active']=False



        starter=True
        resac=""
        texte=''
        win=''
        timec=''
        ffile=''
        cfile=''
        lffile=''
        lcfile=''
        fline=0
        cline=0
        nombrecliq=0
        winame=""
        nmes={}
        dossier={}
        fanal={}
        watcher={}
        fcl=0
        conex=False
        nmes[0,'time']=""
        nmes[0,'mes']=""
        nmes[0,'q']=0
        processactif=""
        powa=False
        prs=0
        enter=False
        tenter=False
        explorer=False
        issyncro=False
        filtre={}
        hmh=False
        zname=""
        zowner=""
        encodings={}
        anaprocspathin={}
        anaprocspatheq={}
        anaprocsnamin={}
        anaprocsnameq={}
        anaficpathin={}
        anaficpatheq={}
        anaficnamin={}
        anaficnameq={}
        anafennamin={}
        anafennameq={}
        listeclient={}
        listeactivite={}
        listeclient['nombre']=0
        listeactivite['nombre']=0
        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
        #hm = pyHook.HookManager()

        #MyButton(self.panel,-1,(47,168),oscurdir+os.sep+'img'+os.sep+'sync-normal.png',oscurdir+os.sep+'img'+os.sep+'sync-rollover.png',oscurdir+os.sep+'img'+os.sep+'appui-sync.png')
        if invisible==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.Region(self.bitmap)
            self.crossRegion = wx.Region(self.cross)
            self.crossoverRegion = wx.Region(self.cross)
            self.syncRegion = wx.Region(self.syncr)
            self.loginRegion = wx.Region(self.loginr)
            self.logoutRegion = wx.Region(self.logoutr)
            self.optionsRegion = wx.Region(self.options)
            self.listeRegion = wx.Region(self.liste)
            self.reduceRegion = wx.Region(self.reduce)

            self.syncRegion.Intersect(self.bitmapRegion)
            self.syncRegion.Offset(49, 168)

            self.loginRegion.Intersect(self.bitmapRegion)
            self.loginRegion.Offset(117, 146)

            self.logoutRegion.Intersect(self.bitmapRegion)
            self.logoutRegion.Offset(49, 146)  

            self.optionsRegion.Intersect(self.bitmapRegion)
            self.optionsRegion.Offset(132, 260)

            self.listeRegion.Intersect(self.bitmapRegion)
            self.listeRegion.Offset(10, 40)

            self.reduceRegion.Intersect(self.bitmapRegion)
            self.reduceRegion.Offset(178, 40)

            self.crossoverRegion.Intersect(self.bitmapRegion)
            self.crossoverRegion.Offset(192, 40)
        
        #self.bitmapRegion.Intersect(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.ClientDC(self)
        if invisible==False:
            #print ('start1')
            self.Bind(wx.EVT_ACTIVATE_APP, self.OnActivate)
            self.dc = wx.ClientDC(self)
            self.Show(True)
#            self.Fit()        
##        self.dc = wx.ClientDC(self)
##        self.dc.DrawBitmap(self.bitmap, 0, 0, True)wx.BufferedDC(wx.ClientDC(self),self.bmp)

#        self.dc.Clear()

        if invisible==False:
            #print ('start2')
            self.tskic = MyTaskBarIcon(self) 
            self.Centre()
            self.Bind(wx.EVT_CLOSE, self.OnClose)
            self.Show(True)
            #print ('start3')
        #obj=DES3.new(str(ElChaloR[0:24]), DES3.MODE_ECB)
        
        #obj=AES.new(str(ElChaloR[0:24]), AES.MODE_CBC,jak)



        self.OnDraw()
        if invisible==True:
            for x in range(458,472):
                try:
                    frame=wx.FindWindowById(x)
                    if frame.IsShown():
                        frame.Hide()
                except:
                    pass
            self.Hide()
    def BringWindowToFront(self):
        try: # it's possible for this event to come when the frame is closed
            self.GetTopWindow().Raise()
        except:
            pass
        
    def OnActivate(self, event):
        # if this is an activate event, rather than something else, like iconize.
        if event.GetActive():
            self.BringWindowToFront()
        event.Skip()
    def chargeDossier(self):
        global fileaccess,zaction,zowner,zeventname,owner,observer,stream,analyse,dossier,explorer,logpath,logfull,watcher,start,poste,user,rept,XTstring,fl,ffile,syncrotip,XCstring,outputfile
        try:
            chemFS= oscurdir + os.sep + "wok"+os.sep+ "conf"+os.sep+"resap.gwh"
            isdos=os.path.isfile(chemFS)
            if isdos==True:
                logfile = open(chemFS,'rb')
            else:
                chemFS= oscurdir + os.sep + "wok"+os.sep+ "need"+os.sep+"zero.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)
        def watch(event):
            global encodings,analyse,start,poste,user,rept,XTstring,fl,syncrotip,ffile,owner,zaction,zeventname,zowner,fileaccess,XCstring,outputfile
            def __init__(self,path_to_watch):
                #Thread.__init__(self)
                #self.path=path_to_watch
                #self.setDaemon(1)
                #self.start()
                pass
            def TSave(self):
                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()


            def Twrite(self,string):
                global rept,XTstring,fl,syncrotip
                try:
                    racine=XTstring.documentElement
                    element =XTstring.createElement("PrsP")
                    element.setAttribute('ReportLine',string)
                    racine.appendChild(element)
                    self.TSave()
                finally:
                    if syncrotip=='cont':
                        Widget.minuteView(string,'full')
            
            def run(self):
                global encodings,fl,user,poste,nombrecliq
                pass
            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
##                ACTIONS = {
##                  1 : "Created",
##                  2 : "Deleted",
##                  3 : "Updated",
##                  4 : "Renamed from something",
##                  5 : "Renamed to something"
##                }
##                # Thanks to Claudio Grondi for the correct set of numbers
##                FILE_LIST_DIRECTORY = 0x0001
##                hDir = win32file.CreateFile (
##                  self.path,
##                  FILE_LIST_DIRECTORY,
##                  win32con.FILE_SHARE_READ | win32con.FILE_SHARE_WRITE,
##                  None,
##                  win32con.OPEN_EXISTING,
##                  win32con.FILE_FLAG_BACKUP_SEMANTICS,
##                  None
##                )
##                while start==True:
##                  #
##                  # ReadDirectoryChangesW takes a previously-created
##                  #  handle to a directory, a buffer size for results,
##                  #  a flag to indicate whether to watch subtrees and
##                  #  a filter of what changes to notify.
##                  #
##                  # NB Tim Juchcinski reports that he needed to up
##                  #  the buffer size to be sure of picking up all
##                  #  events when a large number of files were
##                  #  deleted at once.
##                  #
##                  results = win32file.ReadDirectoryChangesW (
##                    hDir,
##                    1024,
##                    True,
##                    win32con.FILE_NOTIFY_CHANGE_FILE_NAME |
##                     win32con.FILE_NOTIFY_CHANGE_DIR_NAME |
##                     win32con.FILE_NOTIFY_CHANGE_ATTRIBUTES |
##                     win32con.FILE_NOTIFY_CHANGE_SIZE |
##                     win32con.FILE_NOTIFY_CHANGE_LAST_WRITE |
##                     win32con.FILE_NOTIFY_CHANGE_SECURITY,
##                    None,
##                    None
##                  )
##                  for action, file in results:
##                    timec=time.strftime('%m/%d/%y %H:%M:%S')
##                    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()
##                        p = psutil.Process(pr[0])
##                        processactif=p.exe
##                    except:
##                        processactif="None"
##                    full_filename = unchain(os.path.join (self.path, file))
##                    try:
##                        syscod=sys.getdefaultencoding()
##                        tprocess=processactif.decode(syscod)
##                    except:
##                        try:
##                            tprocess=processactif.decode(encodings["Principal"])
##                            #tprocess=unchain(processactif)
##                        except:
##                            try:
##                                tprocess=processactif.decode(encodings["Deuxieme"])
##                            except:
##                                try:
##                                    tprocess=processactif.decode(encodings["Troisieme"])
##                                except:
##                                    try:
##                                        tprocess=processactif.decode(encodings["Quatrieme"])
##                                    except:
##                                        tprocess='None'
##                    full_filenamer = unchain(os.path.join (self.path, file))
##                    try:
##                        syscod=sys.getdefaultencoding()
##                        full_filename=full_filenamer.decode(syscod)
##                    except:
##                        try:
##                            full_filename=full_filenamer.decode('utf-8')
##                        except:
##                            try:
##                                full_filename=full_filenamer.decode(encodings["Principal"])
##                                #tprocess=unchain(processactif)
##                            except:
##                                try:
##                                    full_filename=full_filenamer.decode(encodings["Deuxieme"])
##                                except:
##                                    try:
##                                        full_filename=full_filenamer.decode(encodings["Troisieme"])
##                                    except:
##                                        try:
##                                            full_filename=full_filenamer.decode(encodings["Quatrieme"])
##                                        except:
##                                            full_filename='None'
#                    resac=str(fl)+'#'+str(timec)+'#'+ACTIONS.get (action, "Unknown")+'#'+str(nombrecliq)+'#'+full_filename+'#'+unchain(processactif)+'#'+str(user["ID",int(to)])+'#'+str(poste["PID"])+'\n'
#                    fl+=1
##                    #self.Twrite(resac)
#                    self.Twrite(resac)
            timec=time.strftime('%m/%d/%y %H:%M:%S')
            if event.mask & fsevents.IN_MODIFY:
                action= "Updated"
            elif event.mask & fsevents.IN_ATTRIB:
                action= "Updated"
            elif event.mask & fsevents.IN_CREATE:
                action= "Created"
            elif event.mask & fsevents.IN_DELETE:
                action= "Deleted"
            elif event.mask & fsevents.IN_MOVED_FROM:
                action= "Renamed from something"
            elif event.mask & fsevents.IN_MOVED_TO:
                action= "Renamed to something"
            fileaccess+=1
            if fileaccess==1 or zaction!=action or zeventname!=event.name:
                zaction=action
                zeventname=event.name
                zowner=owner
                try:
                    if encodings["Files1"]!="":
                        fencod=encodings["Files1"]
                        try:
                            tfile=zeventname.decode(fencod)
                        except:
                            try:
                                if encodings["Files2"]!="":
                                    fencod=encodings["Files2"]
                                    tfile=zeventname.decode(pencod)
                                else:
                                    pencod='utf-8'
                                    tfile=zeventname.decode(fencod)
                            except:
                                pencod='utf-8'
                                tfile=zeventname.decode(fencod)
                                
                    else:
                        fencod=sys.getdefaultencoding()
                        tfile=zeventname.decode(fencod)

                except:
                    pencod=sys.getdefaultencoding()
                    tfile=zeventname.decode(fencod)
                try:
                    if encodings["Files1"]!="":
                        fencod=encodings["Files1"]
                        try:
                            appli=owner.decode(fencod)
                        except:
                            try:
                                if encodings["Files2"]!="":
                                    fencod=encodings["Files2"]
                                    appli=owner.decode(pencod)
                                else:
                                    pencod='utf-8'
                                    appli=owner.decode(fencod)
                            except:
                                pencod='utf-8'
                                appli=owner.decode(fencod)
                                
                    else:
                        fencod=sys.getdefaultencoding()
                        appli=owner.decode(fencod)

                except:
                    pencod=sys.getdefaultencoding()
                    appli=owner.decode(fencod) 
                resac=str(fl)+'#'+str(timec)+'#'+action+'#'+str(nombrecliq)+'#'+unchain(tfile)+'#'+unchain(appli)+'#'+str(user["ID",int(to)])+'#'+str(poste["PID"])+'\n'
                fl+=1                   #self.Twrite(resac)
                self.Twrite(resac)
                #print (str(resac))
            if fileaccess==2 and zaction==action and zeventname==event.name:
                fileaccess=0
            #print (str(resac))
        xim=xml.dom.minidom.parseString(drink)
        logfile.close()
        racine=xim.documentElement
        unem = xim.getElementsByTagName('DIR')
        x=1
        dossier['nombre']=0
        observer=Observer()
        dossiers=[]
        #print ('dossier enter')
        for unam in unem:
            dossier['path',x]=unam.getAttribute('PATH')
            dossier['nombre']=x
            #stream=Stream(watch,dossier['path',x],file_events=True)
            dossiers.append(str(dossier['path',x]))
            #print ('dossiers:'+str(dossier['path',x]))
            x+=1
        if x>1:
            zaction=""
            zowner=""
            zeventname=""
            #print ('observer start')
            stream=Stream(watch,*dossiers,file_events=True)
            fileaccess=0
            #print ('observer start1')
            observer.start()
            #print ('observer start2')
            observer.schedule(stream)
            #print ('observer start3')
            #observer.join()
            #print ('observer end')
        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
        #print ('dossier end')

    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):
        global invisible
        #print ('Dshow')
        if invisible==False:
            self.dc.message.Show()
            self.dc.message.SetValue(unicode(mes))
            self.dc.display.Show()
        
    def verifyConfig(self):
        global encodings,invisible,on_open,deltatrsp,oscurdir,jak,ElChaloR,ssyncro,analyse,question,dinac,dtp,dina,slogpath,syncrotip,sconauto,slogrep,Tuser
        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'
            isconfig=os.path.isfile(TchemFSF)
            if isconfig==True:
                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=""
                syncrotip=""
                slogrep=""
                slogpath=""
                sconauto=""
                Tuser=""
                on_open=""
                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
                    if p==5:
                        syncrotip=syncrotip+char
                    if p==6:
                        slogrep=slogrep+char
                    if p==7:
                        slogpath=slogpath+char
                    if p==8:
                        sconauto=sconauto+char
                    if p==9:
                        Tuser=Tuser+char
                    if p==10:
                        on_open=on_open+char
##                    if p==11:
##                        invisible=invisible+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
                    if syncrotip=="True":syncrotip=True
##                    else:sviewer=False
                    if slogrep=="True":slogrep=True
                    else:slogrep=False
                    if sconauto=="True":sconauto=True
                    else:sconauto=False
                    if on_open=="True":on_open=True
                    else:on_open=False
##                    if invisible=="True":invisible=True
##                    else:invisible=False
                    deltatrsp=tdeltatrsp
                    dtp=tdeltatrsp
                    dinac=tdinac
                    dina=dinac
                    self.SetTransparent(int(deltatrsp))
                    self.Show(True)
                else:
                    question=False
                    analyse=False
                    ssyncro=False
                    syncrotip='inact'
                    slogrep=False
                    sconauto=False
                    slogpath=oscurdir+os.sep+'wok'+os.sep+'enc'
                    Tuser=''
                    deltatrsp=255
                    dinac=5
                    dtp=deltatrsp
                    dina=dinac
                    on_open=False
##                    invisible=False
            else:
                question=False
                analyse=False
                ssyncro=False
                syncrotip='inact'
                slogrep=False
                sconauto=False
                slogpath=oscurdir+os.sep+'wok'+os.sep+'enc'
                Tuser=''
                deltatrsp=255
                dinac=5
                dtp=deltatrsp
                dina=dinac
                on_open=False
##                invisible=False
        except:
            question=False
            analyse=False
            ssyncro=False
            syncrotip='inact'
            slogrep=False
            sconauto=False
            slogpath=oscurdir+os.sep+'wok'+os.sep+'enc'
            Tuser=''
            deltatrsp=255
            dinac=5
            dtp=deltatrsp
            dina=dinac
            on_open=False
##            invisible=False
##        try:
##            chemFS=oscurdir+os.sep+'wok'+os.sep+'need'+os.sep+'encodings.xml'
##            ixim = open(chemFS,'r')
##            xim = xml.dom.minidom.parse(ixim)
##            ixim.close()
##            slap=xim.getElementsByTagName('encoding')
##            i=0
##            liste_encoding.append('Aucun')
##            for slip in slap:
##                encodings[i,'encoding']=slip.getAttribute("encoding")
##                encodings[i,'alias']=slip.getAttribute("alias")
##                encodings[i,'language']=slip.getAttribute("language")
##                encodings["total"]=i
##                liste_encoding.append(encodings[i,'language'])
##                #print encodings[i,'language']
##                i=i+1
####                class TransPak:
####                    def write(self, data):
####                        ixom.write(data.encode(str(Str_EncoD)))
####                xim.writexml(TransPak(),encoding=str(Str_EncoD))
##
##        except:
##                encodings[0,'encoding']=sys.getdefaultencoding()
##                encodings[0,'alias']=""
##                encodings[0,'language']="workstation system encoding"
##                liste_encoding.append(encodings[0,'language'])
##                encodings["total"]=0
        try:
            encodings["Process","Active"]=False
            encodings["Files","Active"]=False
            encodings["Title","Active"]=False
            encodings["Process1"]=""
            encodings["Process1",'alias']=""
            encodings["Process1",'language']=""
            encodings["Process2"]=""
            encodings["Process2",'alias']=""
            encodings["Process2",'language']=""
            encodings["Files1"]=""
            encodings["Files1",'alias']=""
            encodings["Files1",'language']=""
            encodings["Files2"]=""
            encodings["Files2",'alias']=""
            encodings["Files2",'language']=""
            encodings["Title1"]=""
            encodings["Title1",'alias']=""
            encodings["Title1",'language']=""
            encodings["Title2"]=""
            encodings["Title2",'alias']=""
            encodings["Title2",'language']=""
            encodings["Title3"]=""
            encodings["Title3",'alias']=""
            encodings["Title3",'language']=""
            TchemFSF=oscurdir+os.sep+'wok'+os.sep+'conf'+os.sep+'languages.gwh'
            isconfig=os.path.isfile(TchemFSF)
            if isconfig==True:
                fft=open(TchemFSF, mode ='rb')
                output = StringIO.StringIO(fft.read())
                decoutput=StringIO.StringIO()
                fft.close()
                Gdecrypt(output,decoutput)
                lines={}
                p=0
                lines = decoutput.getvalue()
                for char in lines:
                    if char=='\t':
                        p+=1
                        continue
                    if char=='\n':
                        glorb=True
                        break
                    if p==0:
                        encodings["Process1"]=str(encodings["Process1"])+str(char)
                        encodings["Process","Active"]=True
                    if p==1:
                        encodings["Process2"]=str(encodings["Process2"])+str(char)
                        encodings["Process","Active"]=True
                    if p==2:
                        encodings["Files1"]=str(encodings["Files1"])+str(char)
                        encodings["Files","Active"]=True
                    if p==3:
                        encodings["Files1"]=str(encodings["Files1"])+str(char)
                        encodings["Files","Active"]=True
                    if p==4:
                        encodings["Title1"]=str(encodings["Title1"])+str(char)
                        encodings["Title","Active"]=True
                    if p==5:
                        encodings["Title2"]=str(encodings["Title2"])+str(char)
                        encodings["Title","Active"]=True
                    if p==6:
                        encodings["Title3"]=str(encodings["Title3"])+str(char)
                        encodings["Title","Active"]=True
                decoutput.close()
                output.close()


        except:
                encodings["Process1"]=sys.getdefaultencoding()
                encodings["Process1",'alias']=""
                encodings["Process1",'language']="workstation system encoding"
                encodings["Process2"]=""
                encodings["Process2",'alias']=""
                encodings["Process2",'language']=""
                encodings["Files1"]=sys.getdefaultencoding()
                encodings["Files1",'alias']=""
                encodings["Files1",'language']="workstation system encoding"
                encodings["Files2"]=""
                encodings["Files2",'alias']=""
                encodings["Files2",'language']=""
                encodings["Title1"]=sys.getdefaultencoding()
                encodings["Title1",'alias']=""
                encodings["Title1",'language']="workstation system encoding"
                encodings["Title2"]=""
                encodings["Title2",'alias']=""
                encodings["Title2",'language']=""
                encodings["Title3"]=""
                encodings["Title3",'alias']=""
                encodings["Title3",'language']=""
                #print 'encoding 0'
    def createRep(self):
        global slogrep,slogpath,oscurdir,rep,rept,crept,ffile,cfile
        def ifexist(rept):
            try:
                islog=os.path.isfile(rept)
##                trylogfile = open(rept, mode ='r')
##                trylogfile.close()
##                return True
                return islog
            except:
                return False
        jour=time.strftime('%d')
        mois=time.strftime('%m')
        annee=time.strftime('%Y')
        if slogrep==True:
            rep=slogpath+os.sep+mois+annee+os.sep+annee+mois+jour
            ttrep=slogpath+os.sep+mois+annee
            fil=annee+mois+jour
        else:
            rep=oscurdir+os.sep+"wok"+os.sep+"enc"+os.sep+mois+annee+os.sep+annee+mois+jour
            ttrep=oscurdir+os.sep+"wok"+os.sep+"enc"+os.sep+mois+annee
            fil=annee+mois+jour
        t=0
        r=True
        if os.access(ttrep,os.F_OK)==True:
            while r==True:
                t=t+1
                rept=str(rep)+str(t)+'.gwh'
                ffile=str(fil)+str(t)
                r=ifexist(rept)
            r=True
            t=0
            while r==True:
                t=t+1
                crept=str(rep)+str(t)+'condensed.gwh'
                cfile=str(fil)+str(t)
                r=ifexist(crept)
            #logfile = open(rept, mode ='a+')
            #clogfile = open(crept, mode ='a+')

        else:
            os.mkdir(ttrep)
            while r==True:
                t=t+1
                rept=str(rep)+str(t)+'.gwh'
                ffile=str(fil)+str(t)
                r=ifexist(rept)
            r=True
            t=0
            while r==True:
                t=t+1
                crept=str(rep)+str(t)+'condensed.gwh'
                cfile=str(fil)+str(t)
                r=ifexist(crept)

    def minuteLine(self,event):
        global reset,start,ssyncro,invisible
        def syncroCheck():
            self.synchro()
        def messageCheck():
            pass
        if reset==True:
            try:
                self.verifyConfig()
                reset=False
            except:
                if invisible==False:
                    self.dc.message.SetValue(unicode(mes)+unicode('config error 1228'))
        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:
            if invisible==False:
                self.dc.message.SetValue(unicode(mes)+unicode('connection error 25456'))
    class minuteLoop(Thread):
        global name,owner,encodings,issyncro,fcl,dina,crept,XCstring,cl,nombrecliq,resac,start,user,poste,sviewer,cfile,ffile,analyse
        def __init__(self,event):
            Thread.__init__(self)
            self.setDaemon(1)
            self.start()    
##        
##    def minuteLoop(self,event):
##        global cl,nombrecliq,texte,computer,logType,verbose,winame,resac,logfile,do,watcher,start,pprocess,prs,processactif

        def CSave(self):
            global XCstring,crept,cfile
            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()
            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,sviewer,dina,fcl,issyncro
            try:
                racine=XCstring.documentElement
                element =XCstring.createElement("PrsP")
                element.setAttribute('ReportLine',string)
                racine.appendChild(element)
                self.CSave()
            finally:
    ##            if str(syncro)=="True" and start==True:
                cl+=1
#                print 'minuteloop-fcl='+str(fcl)+' syncrotip='+str(syncrotip)+' dina='+str(dina)
                if syncrotip=='cont':
                    Widget.minuteView(string,'condensed')
                 #   print 'appel minuteloop'
                if nombrecliq>0:fcl=0
                if syncrotip=='inact' and nombrecliq==0:
                    if int(fcl)==int(dina):
                        if issyncro==True:
                            pass
                        else:
                            Widget.synchro()
                        fcl=0
                    else:fcl=fcl+1
                
        def run(self):
            global encodings,name,owner
            def unchain(string):
                result=""
                if string:
                    x=len(string)
                    if int(x)>100:x=100
                    for x in range(0,x):
                        if string[x] in ["'",'"']:
                            result=result+" "
                        elif string[x] in ["#"]:
                            pass
                        else:result=result+string[x]
                return result
            global cl,nombrecliq,start
            timec=time.strftime('%m/%d/%y %H:%M:%S')
            processactif=owner
##            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()
##                p = psutil.Process(pr[0])
##                processactif=p.exe
##
##            except:
##                processactif="None"
            try:
                if encodings["Process1"]!="":
                    pencod=encodings["Process1"]
                    try:
                        tprocess=processactif.decode(pencod)
                    except:
                        try:
                            if encodings["Process2"]!="":
                                pencod=encodings["Process2"]
                                tprocess=processactif.decode(pencod)
                            else:
                                pencod='utf-8'
                                tprocess=processactif.decode(pencod)
                        except:
                            pencod='utf-8'
                            tprocess=processactif.decode(pencod)
                            
                else:
                    pencod=sys.getdefaultencoding()
                    tprocess=processactif.decode(pencod)

            except:
                pencod=sys.getdefaultencoding()
                tprocess=processactif.decode(pencod)                

            try:
                fen1=name
                tencod=sys.getdefaultencoding()
                if encodings["Title1"]!="":
                    tencod=encodings["Title1"]
                    try:
                        fen=fen1.decode(tencod)
                    except:
                        try:
                            if encodings["Title2"]!="":
                                tencod=encodings["Title2"]
                                fen=fen1.decode(tencod)
                            else:
                                tencod=sys.getdefaultencoding()
                                fen=fen1.decode(tencod)
                                
                        except:
                            try:
                                if encodings["Title3"]!="":
                                    tencod=encodings["Title3"]
                                    fen=fen1.decode(tencod)
                                else:
                                    tencod=sys.getdefaultencoding()
                                    fen=fen1.decode(tencod)
                            except:
                                tencod=sys.getdefaultencoding()
                                fen=fen1.decode(tencod)
                            
                else:
                    tencod=sys.getdefaultencoding()
                    fen=fen1.decode(tencod)

            except:
                tencod=sys.getdefaultencoding()
                fen=fen1.decode(tencod) 

                ##                    fen=unchain(self.event.WindowName).decode('latin-1')
##                    if fen=="":
##                        try:
##                            fen=unchain(ao.Name).decode('latin-1')
##                        except:
##                            fen="None"

##                except:
##                    try:
##                        fen=unchain(ao.Name).decode('latin-1')
##                    except:
##                        try:
##                            fen=unchain(ao.Name)
##                        except:
##                            fen="None"
#            if fen=="":
 #               try:
#                    fen1=name
#                    syscod=sys.getdefaultencoding()
#                    fen=fen1.decode(syscod)
#                except:
#                    try:
#                        fen=fen1.decode(encodings["Principal"])
#                        #tprocess=unchain(processactif)
#                    except:
#                        try:
#                            fen=fen1.decode(encodings["Deuxieme"])
#                        except:
#                            try:
#                                fen=fen1.decode(encodings["Troisieme"])
#                            except:
#                                try:
#                                    fen=fen1.decode(encodings["Quatrieme"])
#                                except:
#                                    fen="None"
            if tprocess=="":
                tprocess="None"
            #print ('minuteloop owner='+str(owner)+' name'+str(name)+' fen='+str(fen))
            resac=str(cl)+'#'+str(timec)+'#'+'minute_maid'+'#'+str(nombrecliq)+'#'+unchain(fen)+'#'+unchain(tprocess)+'#'+str(user["ID",int(to)])+'#'+str(poste["PID"])+'\n'
            #self.Twrite(resac)
            self.Cwrite(resac)
            nombrecliq=0


    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"
                isfiltre=os.path.isfile(chemFS)
                if isfiltre==True:
                    logfile = open(chemFS,'rb')
                else:
                    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"                    
            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').encode('latin-1')
                filtre['nombre']=x
                filtre['Contenant',x]=unam.getAttribute('Contenant').encode('latin-1')
                filtre['Propriete',x]=unam.getAttribute('Propriete').encode('latin-1')
                filtre['Contenu',x]=unam.getAttribute('Contenu').encode('latin-1')
                filtre['Client',x]=unam.getAttribute('Client').encode('latin-1')
                filtre['Prestation',x]=unam.getAttribute('Prestation').encode('latin-1')
                filtre['Prestationid',x]=unam.getAttribute('Prestationid').encode('latin-1')
                filtre["checked",x]=False
                #print filtre['Contenant',x]
                if filtre['Contenant',x]=="Software Path":
                    if filtre['Propriete',x]=="is equal to":
                        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 filtre['Contenant',x]=="contain":
                        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 filtre['Contenant',x]=="Software Name":
                    if filtre['Propriete',x]=="is equal to":
                        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 filtre['Contenant',x]=="contain":
                        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 filtre['Contenant',x]=="File Path":
                    if filtre['Propriete',x]=="is equal to":
                        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 filtre['Propriete',x]=="contain":
                        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 filtre['Contenant',x]=="File Name":
                    if filtre['Propriete',x]=="is equal to":
                        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 filtre['Propriete',x]=="contain":
                        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 filtre['Contenant',x]=="Window Title":
                    #print 'libelle de la fenetre'
                    if filtre['Propriete',x]=="is equal to":
                        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 filtre['Propriete',x]=="contain":
                        #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 ("error in filter loading")



#analyseProcessus(procs),analyseLibelle(libelle),analyseFichier(fichier)


    cocoastart=False
    evtypes = dict(
        NSLeftMouseDown     = 1,
        NSLeftMouseUp       = 2,
        NSRightMouseDown    = 3,
        NSRightMouseUp      = 4,
        NSMouseMoved        = 5,
        NSLeftMouseDragged  = 6,
        NSRightMouseDragged = 7,
        NSMouseEntered      = 8,
        NSMouseExited       = 9,
        NSKeyDown           = 10,
        NSKeyUp             = 11,
        NSFlagsChanged      = 12,
        NSAppKitDefined     = 13,
        NSSystemDefined     = 14,
        NSApplicationDefined = 15,
        NSPeriodic          = 16,
        NSCursorUpdate      = 17,
        NSScrollWheel       = 22,
        NSTabletPoint       = 23,
        NSTabletProximity   = 24,
        NSOtherMouseDown    = 25,
        NSOtherMouseUp      = 26,
        NSOtherMouseDragged = 27
    )

    evtypes_rev = dict([[v,k] for k,v in evtypes.items()])
    class SniffCocoa(Thread):
        global cocoastart,fl,nombrecliq,cocoastart,name,owner,click,user,poste,to,rept,XTstring,fl,sviewer,syncrotip,start,zowner,zname

        def __init__(self):
            global name,owner,click
            Thread.__init__(self)
            name=""
            owner=""
            click=0
            self.key_hook = self.KeyHooker()
            self.mouse_button_hook = self.MouseButtonHooker()
            self.mouse_move_hook = self.MouseMoveHooker()
            self.screen_hook = self.ScreenHooker()
            self.currentApp = None
            objc.setVerbose(1)
            self.setDaemon(1)
            self.start()


        class Hooker(object):
            def __call__(self, *args, **kwargs):
        ##        try:
        ##            evt = kwargs.get('event')
        ##            del kwargs['event'] 
        ##            items = ' '.join( [ x[0]+"="+unicode(x[1]) for x in kwargs.iteritems()] )
        ##            print ("%20s | %22s | %s" % ( self.__class__.__name__, evtypes_rev[evt.type()], items))
        ##        except :
        ##            print ('Horrific error!')
        ##            AppHelper.stopEventLoop()
        ##            sys.exit(0)
              pass

        def KeyHooker(Hooker): pass
        def MouseButtonHooker(Hooker):pass
##            global name,owner
##            print ('mousebuttonhook')
##            if name!="" or owner!="":
##                print ('name:'+str(name)+' owner:'+str(owner))
##                print ('nombrecliq:'+str(nombrecliq))
##                owner=""
##                name=""
        def MouseMoveHooker(Hooker): pass
        def ScreenHooker(Hooker):pass
##            global name,owner
##            print ('name:'+str(name)+' owner:'+str(owner))

        def createAppDelegate (self) :
            #global eventHandler
            #print ('case 12')
            sc = self
            class AppDelegate(NSObject):
                #global eventHandler
                #
                try:
                #def applicationDidFinishLaunching_(self, notification):
                    #print ('case124')
                    mask = (
                              NSKeyDownMask 
                            | NSKeyUpMask
                            | NSLeftMouseDownMask 
                            | NSLeftMouseUpMask
                            | NSRightMouseDownMask 
                            | NSRightMouseUpMask
                            | NSMouseMovedMask 
                            | NSScrollWheelMask
                           )
                    self.eventHandler=Cocoa.NSEvent.addGlobalMonitorForEventsMatchingMask_handler_(mask, sc.handler)
                    #print ('case 13')
                except:
                    #NSEvent.removeMonitor()
                    pass
            return AppDelegate

        def run(self):
            global cocoastart,start
            #print ('case 1')
            #if cocoastart==False:
            #try:
                #NSApplication.sharedApplication()
                #delegate = self.createAppDelegate().alloc().init()
                #NSApp().setDelegate_(delegate)
            #except:
                #pass
            mask = (
                          NSKeyDownMask 
                        | NSKeyUpMask
                        | NSLeftMouseDownMask 
                        | NSLeftMouseUpMask
                        | NSRightMouseDownMask 
                        | NSRightMouseUpMask
                        | NSMouseMovedMask 
                        | NSScrollWheelMask
                       )
            self.eventHandler=Cocoa.NSEvent.addGlobalMonitorForEventsMatchingMask_handler_(mask, self.handler)
            self.workspace = NSWorkspace.sharedWorkspace()
            #start=True
            #cocoastart=True
            #print ('case101')
            #try:
                #AppHelper.stopEventLoop()
                #self.runEventLoop()
                #print ('case1001')
            #except:
                #pass
                #self.stopEventLoop()
                #self.runEventLoop()
                #print ('case1002')
            #print ('case 2')

        def cancel(self):
            global cocoastart
            #print ('case cancel')
            Cocoa.NSEvent.removeMonitor_(self.eventHandler)
            cocoastart=False
            #Cocoa.NSEvent.stopObserving(self.eventHandler)
            #self.eventHandler.Close()
            #print ('case cancel-end')
        def TSave(self):
            global XTstring
            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 Twrite(self,string):
            global rept,XTstring,fl,sviewer,syncrotip
            try:
                racine=XTstring.documentElement
                element =XTstring.createElement("PrsP")
                element.setAttribute('ReportLine',string)
                racine.appendChild(element)
                self.TSave()
            finally:
                if syncrotip=='cont':
                    Widget.minuteView(string,'full')
        def unchain(self,string):
            result=""
            if string:
                x=len(string)
                if int(x)>100:x=100
                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 handler(self, event):
            global cocoastart,fl,nombrecliq,name,owner,click,user,poste,to,zowner,zname
            if cocoastart==True:
                try:
                    #print ('case 3')
                    activeApps = self.workspace.runningApplications()
                    for app in activeApps:
                        #print ('case 31')
                        if app.isActive():
                            #print ('case 32')
                            #if app.isActive():
                            #if app.localizedName() != self.currentApp:
                            #print ('case 33')
                            self.currentApp = app.localizedName()
                            options = kCGWindowListOptionOnScreenOnly 
                            windowList = CGWindowListCopyWindowInfo(options, kCGNullWindowID)

                            for window in windowList:
                                #name=window['kCGWindowName']
                                #owner=window['kCGWindowOwnerName']
                                #print ('windowname:'+str(name)+' owner:'+str(owner))
                                if window['kCGWindowOwnerName'] in self.currentApp:
                                    #print ('case 34')
                                    #geom = window['kCGWindowBounds']
                                    name=window['kCGWindowName']
                                    owner=window['kCGWindowOwnerName']
    ##                                self.screen_hook( event=event,
    ##                                                        name = window['kCGWindowName'],
    ##                                                        owner = window['kCGWindowOwnerName'],
    ##                                                        x = geom['X'], 
    ##                                                        y = geom['Y'], 
    ##                                                        w = geom['Width'], 
    ##                                                        h = geom['Height'])
    ##    
                                    #resac=str(fl)+'#'+str(timec)+'#'+'window_change-mouse'+'#'+str(nombrecliq)+'#'+name+'#'+unchain(owner)+'#'+str(user["ID",int(to)])+'#'+str(poste["PID"])+'\n'
                                    #fl+=1
                                    #Twrite(resac)
                                    #print ('name:'+str(name)+' owner:'+str(owner))
                                    break
                        #except:
                            #print ('case-30003')
                            break

                    #loc = NSEvent.mouseLocation()
                    #print ('case 4')
                    
                    # mouse clicky buttons, NSLeftMouseUp, NSRightMouseUp
                    if event.type() in (NSLeftMouseDown, NSRightMouseDown):
                        #print ('mouse down')
                        click+=1
                        #print ('zowner='+str(zowner)+' owner='+str(owner)+' zname='+str(zname)+' name='+str(name))
                        if click==1 or zowner!=owner or zname!=name:
                            timec=time.strftime('%m/%d/%y %H:%M:%S')
                            nombrecliq+=1
                            try:
                                if encodings["Process1"]!="":
                                    fencod=encodings["Files1"]
                                    try:
                                        appli=owner.decode(fencod)
                                    except:
                                        try:
                                            if encodings["Process2"]!="":
                                                fencod=encodings["Files2"]
                                                appli=owner.decode(pencod)
                                            else:
                                                pencod='utf-8'
                                                appli=owner.decode(fencod)
                                        except:
                                            pencod='utf-8'
                                            appli=owner.decode(fencod)
                                            
                                else:
                                    fencod=sys.getdefaultencoding()
                                    appli=owner.decode(fencod)

                            except:
                                pencod=sys.getdefaultencoding()
                                appli=owner.decode(pencod)                

                            try:
                                fen1=name
                                tencod=sys.getdefaultencoding()
                                if encodings["Title1"]!="":
                                    tencod=encodings["Title1"]
                                    try:
                                        fen=fen1.decode(tencod)
                                    except:
                                        try:
                                            if encodings["Title2"]!="":
                                                tencod=encodings["Title2"]
                                                fen=fen1.decode(tencod)
                                            else:
                                                tencod=sys.getdefaultencoding()
                                                fen=fen1.decode(tencod)
                                                
                                        except:
                                            try:
                                                if encodings["Title3"]!="":
                                                    tencod=encodings["Title3"]
                                                    fen=fen1.decode(tencod)
                                                else:
                                                    tencod=sys.getdefaultencoding()
                                                    fen=fen1.decode(tencod)
                                            except:
                                                tencod='utf-8'
                                                fen=fen1.decode(tencod)
                                            
                                else:
                                    tencod=sys.getdefaultencoding()
                                    fen=fen1.decode(tencod)

                            except:
                                try:
                                    tencod=sys.getdefaultencoding()
                                    fen=fen1.decode(tencod)
                                except:
                                    try:
                                        tencod='utf-8'
                                        fen=fen1.decode(tencod)
                                    except:
                                        fen=fen1
                                

                            #self.mouse_button_hook(event=event, x=loc.x, y=loc.y)
                       #if name!="" or owner!="":
                            #print ('name:'+str(name)+' owner:'+str(owner))
                            #print ('nombrecliq:'+str(nombrecliq))
                            resac=str(fl)+'#'+str(timec)+'#'+'window_change-mouse'+'#'+str(nombrecliq)+'#'+self.unchain(fen)+'#'+self.unchain(appli)+'#'+str(user["ID",int(to)])+'#'+str(poste["PID"])+'\n'
                            #print ('bingo--------------'+str(resac))
                            try:
                                self.Twrite(resac)
                                fl+=1
                                #print (str(resac))
                            except:
                                pass
                                #print ('erreur resac')
                            zowner=owner
                            zname=name
                            #owner=""
                            #name=""
                        if click==2 and zowner==owner and zname==name:
                            click=0
        
     
                    #elif event.type() ==NSApplicationDefined:
                        #if name!="" or owner!="":
                            #print ('appdefined name:'+str(name)+' owner:'+str(owner))
                            #print ('nombrecliq:'+str(nombrecliq))
                            #owner=""
                            #name=""                       

                    # mouse scrolly buttons 
                    elif event.type() == NSScrollWheel:
                        pass
                        #print ('case 5')
                        #if event.deltaY() > 0 and event.deltaY() < 0:
                            #self.mouse_button_hook(event=event, x=loc.x, y=loc.y)
                        #if event.deltaX() > 0 and event.deltaX() < 0:
                            #self.mouse_button_hook(event=event, x=loc.x, y=loc.y)

                    # keys down
                    elif event.type() in ( NSKeyDown, NSKeyUp ):
                        #print ('case 6')
                        #flags = event.modifierFlags()
                        modifiers = [] # OS X api doesn't care it if is left or right
                        if (flags & NSControlKeyMask):
                            modifiers.append('CONTROL')
                        if (flags & NSAlternateKeyMask):
                            modifiers.append('ALTERNATE')
                        if (flags & NSCommandKeyMask):
                            modifiers.append('COMMAND')

                        #self.key_hook(event=event, key=event.keyCode(), char=str(event.keyCode()), mods=modifiers, is_repeat=event.isARepeat())

                    # Mouse moved
                    #elif event.type() == NSMouseMoved:
                        #self.mouse_move_hook(event=event, x=loc.x, y=loc.y)
                    else:
                        pass

                except ( KeyboardInterrupt ):
                    print ('handler', KeyboardInterrupt)
                    #NSEvent.removeMonitor()
        def CStop():
            #print ('sniffer stop1')
            Cocoa.NSEvent.removeMonitor()


    def autoStart(self):
        global cocoastart,encodings,invisible,on_open,connec,conex,cursex,mes,to,start,hm,oscurdir,jak,ElChaloR,poste,user,Tuser,postes,ssyncro,syncrotip,timer,user_id,ffile,users,dusers,hmh,invisible
        TchemFSF=oscurdir+os.sep+'wok'+os.sep+'conf'+os.sep+'local.gwh'
        isconfig=os.path.isfile(TchemFSF)
        #print '1'
        if isconfig==True:
            #print '1.2'
            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
            #print '1.3'
            poste={}
            user={}
            l=0
            poste["PID"]=""
            poste["ID"]=""
            poste["posteNAME"]=""
            poste["Date"]=""
            poste["GUID"]=""
            poste["ADMINID"]=""
            users['serverip']=""
            users['serverdomain']=""
            T=False
            ip_enter=False
            go_on=True
            for char in lines:
                if char=='\t':
                    p+=1
                    ip_enter=False
                    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 and char in['i','p',':']:
                    ip_enter=True
                    go_on=False
                    continue
                    
                if go_on==False:
                    if ip_enter==True and p==0 and l==0:
                        users['serverip']=users['serverip']+char
                    if p==1 and l==0:users['serverdomain']=users['serverdomain']+char
                    if p==2 and l==0:poste["PID"]=poste["PID"]+char
                    if p==3 and l==0:poste["ID"]=poste["ID"]+char
                    if p==4 and l==0:poste["posteNAME"]=poste["posteNAME"]+char
                    if p==5 and l==0:poste["Date"]=poste["Date"]+char
                    if p==6 and l==0:poste["GUID"]=poste["GUID"]+char
                    if p==7 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
                else:
                    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
                    users['serverip']='62.210.195.95'
                    users['serverdomain']='http://www.chronosmonitor.com'
    ##            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
            #print '1.4'
            for x in range(1,l):
    ##                pass1 = hashlib.sha1(powa).digest()
    ##                pass2 = hashlib.sha1(pass1).hexdigest()                
                #print user["pass",x]
                #print Tuser+':'+user["nom",x]+' '+user["prenom",x]
                if user["nom",x]+' '+user["prenom",x]==Tuser:
                    #print '1.5'
                    user_id=user["ID",x]
                    poste_pid=poste["ID"]
                    poste["PID"]=poste["ID"]
                    user["nombre"]=l
                    to=int(x)
                    found=True
                    #print '1.6'
                    try:
                        conn_string = "host='"+str(users['serverip'])+"' dbname='chronos-monitor.com' user='chronos' password='gortex855'"
                        conn = psycopg2.connect(conn_string)                        
                        curs = conn.cursor()
                        result=curs.execute("SELECT config,auto,export,password,sfiltre FROM droits_ut WHERE id='"+str(user_id)+"';" )
                        result=curs.fetchone()
                        u=1
                        #print '1.7'
                        if result:
                            active=True
                            p=0
                            dusers['config']=""
                            dusers['auto']=""
                            dusers['export']=""
                            dusers['password']=""
                            dusers['sfiltre']=""
                            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']+str(chain)
                                if p==4:dusers['sfiltre']=dusers['sfiltre']+str(chain)
                                p+=1
                            dusers['active']=True
                    except:
                        dusers['active']=False
                        conex=False
                        syncrotip='manu'                        
                    #print '1.7.1'
                    break

                    #print 'gagne'
            if found==False or str(found) == "not":
                #print 'not1'
                if found==False:
                    mes='user name error'
                    if invisible==False:
                        self.dc.message.SetValue(unicode('user name error'))
                elif str(found)=="not":
                    mes='enter password'
                    if invisible==False:
                        self.dc.message.SetValue(unicode('enter password'))
            elif int(unchar(poste["Date"]))<int(unchar(time.strftime('%Y-%m-%d')))and conex==True:
                #try:
                #print 'good 2'
                if poste["Date"]:
                    conn_string = "host='"+str(users['serverip'])+"' dbname='chronos-monitor.com' user='chronos' password='gortex855'"
                    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)
                        #print "internet connection probably wrong"
                        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='error opening file local.gwh'
                                
                                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='ip:'+str(users[serverip])+'\t'+str(users[serverdomain])+'\t'+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+'-encryption error'
                                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
                                    #print ('1.8')
##                                    if hmh==False:
##                                        try:
##                                            hm.MouseAllButtonsDown = OnMouseEvent
##                                            #hm.MouseMove = NoEvent
##                                            #hm.MouseLeftDown = OnMouseEvent
##                                           
##                                            #hm.MouseRightDown = OnMouseEvent
##                                            # set the hook user["ID",to]
##                                            hm.HookMouse()
##                                            print '1.9'
##                                            #pythoncom.PumpMessages
##                                        finally:
##
                                    #hmh=True
                                    #if cocoastart==False:
                                        #sc = SniffCocoa()
                                        #sc.run()
                                    cocoastart=True
                                    mes='-'+user["nom",to]+'-connected-'
                                    #self.dc.message.SetEditable(True)
                                    if invisible==False:
                                        self.dc.message.SetValue(unicode(mes))
                                    computer = None
                                    logType = "Security"
                                    verbose = 0
                                    #elf.dc.message.SetEditable(False)
                                    start=True
                                    if ssyncro==True:
                                        self.chargeDossier()
                                        #print ('charge dossier')
                                    #else:
                                        #print ('ssyncro off')
                                    timer.Start(milliseconds=60000, oneShot=False)
                                    #minuteView(resac)
                                    if syncrotip=='cont':
                                        try:
                                            conn_string = "host='"+str(users['serverip'])+"' dbname='chronos-monitor.com' user='chronos' password='gortex855'"
                                            connec = psycopg2.connect(conn_string)
                                            connec.set_client_encoding('UTF8')
                                            cursex = connec.cursor()
                                            conex=True
                                            self.minuteView(resac,'full')
                                            self.minuteView(resac,'condensed')
                                        except:
                                            mes="reseau indisponible, syncro off"
                                            if invisible==False:
                                                self.dc.message.SetValue(unicode(mes))
                                            conex=False
                                            syncrotip='manu'
                                    if str(on_open)=="True" or on_open==True:
                                        #print '1245478'
                                        try:
                                            frame=wx.FindWindowById(444)
                                            if frame.IsShown():
                                                frame.Hide()
                                                #print '12457810'
                                            #else:
                                                #print '12457814'
                                            #print '12457812'
                                        except:
                                            pass  

                                    #timerF.Start(milliseconds=10000, oneShot=False)
                            else:
                                line1="Licence is out-of-date."
                                line2="Ask the renewal" 
                                line3="to your administrator."
                                try:
                                    dialogframe = wx.FindWindowById(465)
                                    dialogframe.Close()
                                    WizardEnd(None, 465, 'Chronos Monitor Configuration')            
                                except:
                                    WizardEnd(None, 465, 'Chronos Monitor Configuration')
                        else:
                            line1="Licence is out-of-date."
                            line2="Ask the renewal" 
                            line3="to your administrator."
                            try:
                                dialogframe = wx.FindWindowById(465)
                                dialogframe.Close()
                                WizardEnd(None, 465, 'Chronos Monitor Configuration')            
                            except:
                                WizardEnd(None, 465, 'Chronos Monitor Configuration')
                    try:
                        curs.close()
                        conn.close()
                    except:
                        pass
    ##                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:
                #print '2.1'
                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)
                self.minuteSave(self)
    ##            try:
                #print '2.2'
                try:
##                    if hmh==False:
##                        try:
##                            hm.MouseAllButtonsDown = asOnMouseEvent
##                            #hm.MouseMove = NoEvent
##                            # set the hook user["ID",to]
##                            hm.HookMouse()
##                            #print '2.3'
##                            #pythoncom.PumpMessages
##                        finally:
##                            hmh=True
                    
                    # watch for all mouse events
                    #print '2.4'
                    #pythoncom.PumpMessages()
                    if cocoastart==False:
                        cocoastart=True
                    mes='-'+user["nom",to]+'-connecte-'
                    #self.dc.message.SetEditable(True)
                    if str(on_open)=="False" or on_open==False:
                        if invisible==False:
                            self.dc.message.SetValue(unicode(mes))
                    #elf.dc.message.SetEditable(False)
                    start=True
                    #print ('2.5')
                    if ssyncro==True:
                        self.chargeDossier()
                        #print ('charge dossier')
                    #else:
                        #print ('ssyncro off')
                    #print ('2.6')
                    timer.Start(milliseconds=60000, oneShot=False)

                    if syncrotip=='cont':
                        try:
                            conn_string = "host='"+str(users['serverip'])+"' dbname='chronos-monitor.com' user='chronos' password='gortex855'"
                            connec = psycopg2.connect(conn_string)
                            connec.set_client_encoding('UTF8')
                            cursex = connec.cursor()
                            conex=True
                            self.minuteView(resac,'full')
                            self.minuteView(resac,'condensed')
                            #print 'good conex'
                        except:
                            mes="reseau indisponible, syncro off"
                            if invisible==False:
                                self.dc.message.SetValue(unicode(mes))
                            conex=False
                            syncrotip='manu'
                    if str(on_open)=="True" or on_open==True:
                        #print '1245478'
                        try:
                            frame=wx.FindWindowById(444)
                            if frame.IsShown():
                                frame.Hide()
                                #print '12457810'
                            #else:
                                #print '12457814'
                            #print '12457812'
                        except:
                            pass                            

                    #timerF.Start(milliseconds=10000, oneShot=False)
                except:
                    
                    pass


                #timerF.Start(milliseconds=10000, oneShot=False)
    ##            except:
    ##                
    ##                self.dc.message.SetValue('erreur de connection')




            
    def OnClose(self, event):
        self.tskic.Destroy()
        self.Destroy()


    def SetNoteShape(self, *event):
        global invisible
        #region=wx.RegionColour(self.bitmap,'#000000',0)
        region = wx.Region(self.bitmap)
        self.hasShape=self.SetShape(region)
        #if invisible==False:
            
        
    def OnKey(self,event):
        global powa
        powa=event.GetString()

    def OnClicked(self, event):
        #print 'event reached frame class'
        event.Skip()

    def Draw(self):
        global pgb
        #print ('draw1')
        wx.BufferedDC(wx.ClientDC(self),self.bmp)
        self.dc.SetFont(self.font)
        self.dc.SetTextForeground('WHITE')
        pgb=wx.Gauge(self, -1 ,pos=(15,12),size=(188,21))
        pgb.Hide()
        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.message.SetBackgroundColour('#EAEAE9')
        
        #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)
        #print ('draw2')

        #self.dc.nkey.SetValue("CLEF DACTIVATION")#EAEAE9
        self.dc.display.Bind(wx.EVT_TEXT, self.OnKey)
        #print ('draw3')
##        try: # it's possible for this event to come when the frame is closed
##            self.GetTopWindow().Raise()
##        except:
##            pass

    def OnPaint(self, event):
        global analyse,sconauto,invisible
##        print ('ondraw1')
##        self.verifyConfig()
##        self.createRep()
        if invisible==False:
            wx.BufferedPaintDC(self,self.bitmap)
##            self.Draw()
##            print('ondraw2')
##        if analyse==True:
##            print('ondraw23')
##            self.chargeFiltres()
##        if sconauto==True:self.autoStart()
##        if syncrotip=='cont':
##            print('ondraw24')
##            self.chargeDonnees()
##            self.synchro()
##        print ('ondraw5') 
        event.Skip()
    def chargeDonnees(self):
        global listeclient,listeactivite,users,poste
        #print ('charge donnee')
        try:
            TchemFSF=oscurdir+os.sep+'wok'+os.sep+'conf'+os.sep+'local.gwh'
            isconfig=os.path.isfile(TchemFSF)
            if isconfig==True:
                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
                users['serverip']=""
                users['serverdomain']=""
                poste["PID"]=""
                poste["ID"]=""
                poste["posteNAME"]=""
                poste["Date"]=""
                poste["GUID"]=""
                poste["ADMINID"]=""
                T=False
                ip_enter=False
                go_on=True
                for char in lines:
                    if char=='\t':
                        p+=1
                        ip_enter=False
                        continue
                    if char=='\n':
                        break
                    if p==0 and l==0 and char in['i','p',':']:
                        ip_enter=True
                        go_on=False
                        continue
                        
                    if go_on==False:
                        if ip_enter==True and p==0 and l==0:
                            users['serverip']=users['serverip']+char
                        if p==1 and l==0:users['serverdomain']=users['serverdomain']+char
                        if p==2 and l==0:poste["PID"]=poste["PID"]+char
                        if p==3 and l==0:poste["ID"]=poste["ID"]+char
                        if p==4 and l==0:poste["posteNAME"]=poste["posteNAME"]+char
                        if p==5 and l==0:poste["Date"]=poste["Date"]+char
                        if p==6 and l==0:poste["GUID"]=poste["GUID"]+char
                        if p==7 and l==0:poste["ADMINID"]=poste["ADMINID"]+char
                    else:
                        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
                        users['serverip']='88.191.122.246'
                        users['serverdomain']='http://www.chronosmonitor.com'
                if poste["ADMINID"]!="":    
                    conn_string = "host='"+str(users['serverip'])+"' dbname='chronos-monitor.com' user='chronos' password='gortex855'"
                    conn = psycopg2.connect(conn_string)
                    curs = conn.cursor()
                    result=curs.execute("SELECT nomsoc FROM clients WHERE idadmin='"+str(poste["ADMINID"])+"';" )
                    result=curs.fetchall()
                    x=0
                    if result:
                        for chain in result:
                            Tclient=""
                            for char in chain:
                                Tclient=Tclient+str(char)
                            listeclient[x]=Tclient
                            listeclient['nombre']=x
                            x+=1
                    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
                    x=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[x,'prestation']=T0presta
                            listeactivite[x,'id']=T0idpresta
                            listeactivite['nombre']=x
                            x+=1
                            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[x,'prestation']=T1presta
                                    listeactivite[x,'id']=T1idpresta
                                    listeactivite['nombre']=x
                                    x+=1
                                    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[x,'prestation']=T2presta
                                            listeactivite[x,'id']=T2idpresta
                                            listeactivite['nombre']=x
                                            x+=1
                                            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="error : run configuration wizard before"
            else:
                message="error : run configuration wizard before"
        except:
            message="internet connection required"
    def OnDraw(self):
        global analyse,sconauto
        #wx.BufferedDC(wx.ClientDC(self),self.bmp)
        #print ('ondraw1')
        self.verifyConfig()
        self.createRep()
        #if ssyncro==True:
            
        if invisible==False:
            self.Draw()
            #print ('ondraw2')
        if analyse==True:
            #print ('ondraw23')
            self.chargeFiltres()
        sc=self.SniffCocoa()
        sc.run()
        if sconauto==True:self.autoStart()
        if syncrotip=='cont':
            #print ('ondraw24')
            self.chargeDonnees()
            self.synchro()

        #print ('ondraw5')
        #pass

        
        
    class minuteView(Thread):
        global syncrotip,cursex,connec,user,poste,ffile,cfile,anafennamin,anafennameq,anaprocspathin,anaprocspatheq,anaprocsnamin,anaprocsnameq,anaficpathin,anaficpatheq,anaficnamin,anaficnameq,fanal,analyse,mes,listeclient,listeactivite,slogpath
        def __init__(self,string,tip):
            Thread.__init__(self)
            self.setDaemon(1)
            self.line=string
            self.type=tip
            self.start()
        def run(self):
            global cursex,connec,user,poste,ffile,cfile,anafennamin,anafennameq,anaprocspathin,anaprocspatheq,anaprocsnamin,anaprocsnameq,anaficpathin,anaficpatheq,anaficnamin,anaficnameq,fanal,analyse,mes,listeclient,listeactivite,slogpath,syncrotip
            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
            def formatFanal():
                global fanal
                fanal['client']="None"
                fanal['prestation']="None"

            def analyseLibelle(libelle):
                global anafennamin,anafennameq,fanal,listeclient,listeactivite
                def unchain(nstring):
                    try:
                        t=len(nstring)
                        result=""
                        string=nstring.decode('latin-1').encode('latin-1')
                        for x in range(0,t):
                            if string[x] in ['é','è','ê']:
                                result=result+'e'
                            elif string[x] in ['î','ï']:
                                result=result+'i'
                            elif string[x] in ['â','ä','à']:
                                result=result+'a'
                            elif string[x] in ['ô','ö']:
                                result=result+'o'
                            else:result=result+string[x]
                        return result
                    except:
                        return nstring
                
                for x in range(1,anafennamin['count']+1):
                    if unchain(anafennamin['contenu',x]).upper()==unchain(libelle).upper():
                        if anafennamin['client',x]!='undefined':
                            fanal['client']=anafennamin['client',x]
                        if anafennamin['prestation',x]!='non défini':
                            fanal['prestation']=anafennamin['prestationid',x]
                    if anafennamin['contenu',x]=='Customer Name' and anafennamin['client',x]=='Customer mentioned':
                        for u in range(0,listeclient['nombre']):
                            if unchain(listeclient[u]).upper() ==unchain(libelle).upper():
                                fanal['client']=listeclient[u]
                    if anafennamin['contenu',x]=='Service Name' and anafennamin['client',x]=='Service mentioned':
                        for u in range(0,listeactivite['nombre']):
                            if unchain(listeactivite[u,'prestation']).upper() ==unchain(libelle).upper():
                                fanal['prestation']=listeactivite[u,'id']

                for x in range(1,anafennameq['count']+1):
    ##                print unchain(anafennameq['contenu',x]).upper()
    ##                print unchain(libelle).upper()
                    if unchain(anafennameq['contenu',x]).upper() in unchain(libelle).upper():
                        if anafennameq['client',x]!='undefined':
                            fanal['client']=anafennameq['client',x]
                        if anafennameq['prestation',x]!='undefined':
                            fanal['prestation']=anafennameq['prestationid',x]
                    if anafennameq['contenu',x]=='Customer Name' and anafennameq['client',x]=='Customer mentioned':
                        for u in range(0,listeclient['nombre']):
                            if unchain(listeclient[u]).upper() in unchain(libelle).upper():
                                fanal['client']=listeclient[u]
                    if anafennameq['contenu',x]=='Service Name' and anafennameq['client',x]=='Service mentioned':
                        for u in range(0,listeactivite['nombre']):
                            if unchain(listeactivite[u,'prestation']).upper() in unchain(libelle).upper():
                                fanal['prestation']=listeactivite[u,'id']
            def analyseProcessus(procs):
                global anaprocspathin,anaprocspatheq,anaprocsnamin,anaprocsnameq,fanal,listeclient,listeactivite
                def unchain(nstring):
                    try:
                        t=len(nstring)
                        result=""
                        string=nstring.decode('latin-1').encode('latin-1')
                        for x in range(0,t):
                            if string[x] in ['é','è','ê']:
                                result=result+'e'
                            elif string[x] in ['î','ï']:
                                result=result+'i'
                            elif string[x] in ['â','ä','à']:
                                result=result+'a'
                            elif string[x] in ['ô','ö']:
                                result=result+'o'
                            else:result=result+string[x]
                        return result
                    except:
                        return nstring
                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 unchain(anaprocspathin['contenu',x]).upper()==unchain(processpath).upper():
                        if anaprocspathin['client',x]!='undefined':
                            fanal['client']=anaprocspathin['client',x]
                        if anaprocspathin['prestation',x]!='undefined':
                            fanal['prestation']=anaprocspathin['prestationid',x]
                    if anaprocspathin['contenu',x]=='Customer Name' and anaprocspathin['client',x]=='Customer mentioned':
                        for u in range(0,listeclient['nombre']):
                            if unchain(processpath).upper()==unchain(listeclient[u]).upper():
                                fanal['client']=listeclient[u]
                    if anaprocspathin['contenu',x]=='Service Name' and anaprocspathin['client',x]=='Service mentioned':
                        for u in range(0,listeactivite['nombre']):
                            if unchain(processpath).upper()==unchain(listeactivite[u,'prestation']).upper():
                                fanal['prestation']=listeactivite[u,'id']
                for x in range(1,anaprocspatheq['count']+1):
                    if unchain(anaprocspatheq['contenu',x]).upper() in unchain(processpath).upper():
                        if anaprocspatheq['client',x]!='undefined':
                            fanal['client']=anaprocspatheq['client',x]
                        if anaprocspatheq['prestation',x]!='non défini':
                            fanal['prestation']=anaprocspatheq['prestationid',x]
                    if anaprocspatheq['contenu',x]=='Customer Name' and anaprocspatheq['client',x]=='Customer mentioned':
                        for u in range(0,listeclient['nombre']):
                            if unchain(listeclient[u]).upper() in unchain(processpath).upper():
                                fanal['client']=listeclient[u]
                    if anaprocspatheq['contenu',x]=='Service Name' and anaprocspatheq['client',x]=='Service mentioned':
                        for u in range(0,listeactivite['nombre']):
                            if unchain(listeactivite[u,'prestation']).upper() in unchain(processpath).upper():
                                fanal['prestation']=listeactivite[u,'id']
                for x in range(1,anaprocsnamin['count']+1):
                    if unchain(anaprocsnamin['contenu',x]).upper()==unchain(processfile).upper():
                        if anaprocsnamin['client',x]!='undefined':
                            fanal['client']=anaprocsnamin['client',x]
                        if anaprocsnamin['prestation',x]!='undefined':
                            fanal['prestation']=anaprocsnamin['prestationid',x]
                    if anaprocsnamin['contenu',x]=='Customer Name' and anaprocsnamin['client',x]=='Customer mentioned':
                        for u in range(0,listeclient['nombre']):
                            if unchain(listeclient[u]).upper() ==unchain(processfile).upper():
                                fanal['client']=listeclient[u]
                    if anaprocsnamin['contenu',x]=='Service Name' and anaprocsnamin['client',x]=='Service mentioned':
                        for u in range(0,listeactivite['nombre']):
                            if unchain(listeactivite[u,'prestation']).upper() == unchain(processfile).upper():
                                fanal['prestation']=listeactivite[u,'id']
                for x in range(1,anaprocsnameq['count']+1):
                    if unchain(anaprocsnameq['contenu',x]).upper() in unchain(processfile).upper():
                        if anaprocsnameq['client',x]!='undefined':
                            fanal['client']=anaprocsnameq['client',x]
                        if anaprocsnameq['prestation',x]!='non défini':
                            fanal['prestation']=anaprocsnameq['prestationid',x]
                    if anaprocsnameq['contenu',x]=='Customer Name' and anaprocsnameq['client',x]=='Customer mentioned':
                        for u in range(0,listeclient['nombre']):
                            if unchain(listeclient[u]).upper() in unchain(processfile).upper():
                                fanal['client']=listeclient[u]
                    if anaprocsnameq['contenu',x]=='Service Name' and anaprocsnameq['client',x]=='Service mentioned':
                        for u in range(0,listeactivite['nombre']):
                            if unchain(listeactivite[u,'prestation']).upper() in unchain(processfile).upper():
                                fanal['prestation']=listeactivite[u,'id']
            def analyseFichier(fichier):
                global anaficpathin,anaficpatheq,anaficnamin,anaficnameq,fanal,listeclient,listeactivite
                def unchain(nstring):
                    try:
                        t=len(nstring)
                        result=""
                        string=nstring.decode('latin-1').encode('latin-1')
                        for x in range(0,t):
                            if string[x] in ['é','è','ê']:
                                result=result+'e'
                            elif string[x] in ['î','ï']:
                                result=result+'i'
                            elif string[x] in ['â','ä','à']:
                                result=result+'a'
                            elif string[x] in ['ô','ö']:
                                result=result+'o'
                            else:result=result+string[x]
                        return result
                    except:
                        return nstring
                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 unchain(anaficpathin['contenu',x]).upper()==unchain(filepath).upper():
                        if anaficpathin['client',x]!='undefined':
                            fanal['client']=anaficpathin['client',x]
                        if anaficpathin['prestation',x]!='undefined':
                            fanal['prestation']=anaficpathin['prestationid',x]
                    if anaficpathin['contenu',x]=='Customer Name' and anaficpathin['client',x]=='Customer mentioned':
                        for u in range(0,listeclient['nombre']):
                            if unchain(listeclient[u]).upper() == unchain(filepath).upper():
                                fanal['client']=listeclient[u]
                    if anaficpathin['contenu',x]=='Service Name' and anaficpathin['client',x]=='Service mentioned':
                        for u in range(0,listeactivite['nombre']):
                            if unchain(listeactivite[u,'prestation']).upper() == unchain(filepath).upper():
                                fanal['prestation']=listeactivite[u,'id']
                for x in range(1,anaficpatheq['count']+1):
                    if unchain(anaficpatheq['contenu',x]).upper() in unchain(filepath).upper():
                        if anaficpatheq['client',x]!='undefined':
                            fanal['client']=anaficpatheq['client',x]
                        if anaficpatheq['prestation',x]!='non défini':
                            fanal['prestation']=anaficpatheq['prestationid',x]
                    if anaficpatheq['contenu',x]=='Customer Name' and anaficpatheq['client',x]=='Customer mentioned':
                        for u in range(0,listeclient['nombre']):
                            if unchain(listeclient[u]).upper() in unchain(filepath).upper():
                                fanal['client']=listeclient[u]
                    if anaficpatheq['contenu',x]=='Service Name' and anaficpatheq['client',x]=='Service mentioned':
                        for u in range(0,listeactivite['nombre']):
                            if unchain(listeactivite[u,'prestation']).upper() in unchain(filepath).upper():
                                fanal['prestation']=listeactivite[u,'id']
                for x in range(1,anaficnamin['count']+1):
                    if unchain(anaficnamin['contenu',x]).upper()==unchain(filefile).upper():
                        if anaficnamin['client',x]!='undefined':
                            fanal['client']=anaficnamin['client',x]
                        if anaficnamin['prestation',x]!='undefined':
                            fanal['prestation']=anaficnamin['prestationid',x]
                    if anaficnamin['contenu',x]=='Customer Name' and anaficnamin['client',x]=='Customer mentioned':
                        for u in range(0,listeclient['nombre']):
                            if unchain(listeclient[u]).upper() == unchain(filefile).upper():
                                fanal['client']=listeclient[u]
                    if anaficnamin['contenu',x]=='Service Name' and anaficnamin['client',x]=='Service mentioned':
                        for u in range(0,listeactivite['nombre']):
                            if unchain(listeactivite[u,'prestation']).upper() in unchain(filefile).upper():
                                fanal['prestation']=listeactivite[u,'id']
                for x in range(1,anaficnameq['count']+1):
                    if unchain(anaficnameq['contenu',x]).upper() == unchain(filefile).upper():
                        if anaficnameq['client',x]!='undefined':
                            fanal['client']=anaficnameq['client',x]
                        if anaficnameq['prestation',x]!='undefined':
                            fanal['prestation']=anaficnameq['prestationid',x]
                    if anaficnameq['contenu',x]=='Customer Name' and anaficnameq['client',x]=='Customer mentioned':
                        for u in range(0,listeclient['nombre']):
                            if unchain(listeclient[u]).upper() in unchain(filefile).upper():
                                fanal['client']=listeclient[u]
                    if anaficnameq['contenu',x]=='Service Name' and anaficnameq['client',x]=='Service mentioned':
                        for x in range(0,listeactivite['nombre']):
                            if unchain(listeactivite[u,'prestation']).upper() in unchain(filefile).upper():
                                fanal['prestation']=listeactivite[u,'id']


            Txzorbl={}
            final={}
            ses=0
            p=0
            Txzorbl[p]=""
            ln=len(self.line)
            for x in range(0,ln):
                char=self.line[x:x+1]
                if char=="#":
                    p+=1
                    Txzorbl[p]=""
                else:
                    Txzorbl[p]=Txzorbl[p]+char
            try:
             #   print 'minute view1'
                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
            #    print 'minutevie2'
                if self.type=="full":
                    intostr="""INSERT INTO logfull (file,line,date, heure, nomfenetre, processus, chemin, clicks, client,activite,action,userid,posteid,final_userid) VALUES """
                    sfile=ffile
                elif self.type=="condensed":
                    intostr="""INSERT INTO logcondensed (file,line,date, heure, nomfenetre, processus, chemin, clicks, client,activite,action,userid,posteid,final_userid) VALUES """
                    sfile=cfile
            #    print 'minute view3'
                if str(Txzorbl[2])=='user_begin':
                    ses+=1
                    action=Txzorbl[2]
                    userid=Txzorbl[3]
                    line=Txzorbl[0]
                    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+"('"+sfile+"','"+ line+"','"+date+"','"+ houre+"','"+ fen+"','"+ procs+"','"+chemin + "', '0', '','','debut session','"+final['session','userid',str(ses)]+"','"+final['session','postepid',str(ses)]+"','"+str(poste['ADMINID'])+"');"
                    inscript=True
            #    print 'minuteview4'
                if str(Txzorbl[2])=='user_exit':
                    action=Txzorbl[2]
                    userid=Txzorbl[3]
                    line=Txzorbl[0]
                    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+"('"+sfile+"','"+ line+"','"+date+"','"+ houre+"','"+ fen+"','"+ procs+"','"+chemin+"', '0', '','','fin session','"+final['session','userid',str(ses)]+"','"+final['session','postepid',str(ses)]+"','"+str(poste['ADMINID'])+"');"
                    inscript=True

                if str(Txzorbl[2])=='widget_stop':
                    action=Txzorbl[2]
                    userid=Txzorbl[3]
                    line=Txzorbl[0]
                    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+"('"+sfile+"','"+ line+"','"+date+"','"+ houre+"','"+ fen+"','"+ procs+"','"+chemin+"', '0', '','','fin session','"+final['session','userid',str(ses)]+"','"+final['session','postepid',str(ses)]+"','"+str(poste['ADMINID'])+"');"
                    inscript=True
                if str(Txzorbl[2])=='minute_maid':
                    action=Txzorbl[2]
                    line=Txzorbl[0]
                    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
                    formatFanal()
                    if analyse==True:
                        analyseProcessus(Txzorbl[5])
                        analyseLibelle(Txzorbl[4])
                    intostr=intostr+"('"+sfile+"','"+ line+"','"+date+"','" +houre+"','"+ fen+"','"+ procs+"','"+chemin+"', '"+str(ncl)+"','','','minute_maid','"+userid+"','"+postepid+"','"+str(poste['ADMINID'])+"');"
                    inscript=True
           #     print 'minuteviwe5'
                if str(Txzorbl[2])=='window_change-mouse':
                    action=Txzorbl[2]
                    line=Txzorbl[0]
                    chemin="None"
             #       print 'mv51'
                    try:
                        userid=Txzorbl[6]
                    except:
                        userid=0
                    try:
                        postepid=poste['ID']
                    except:
                        postepid=poste['PID']
             #       print 'mv52'
                    try:
                        procs=chain(Txzorbl[5])
                    except:
                        procs="None"
               #     print 'mv53'
                    try:
                        ncl=0
                        fen=chain(unchain(Txzorbl[4]))
                    except:
                        fen="None"
            #        print 'mv54'
                    try:
                        ncl=chain(unchain(Txzorbl[3]))
                    except:
                        ncl=0
               #     print 'mv55'
                    formatFanal()
             #       print 'mv56'
                    if analyse==True:
                #        print 'mv57'
                        analyseProcessus(Txzorbl[5])
             #           print 'mv58'
                        analyseLibelle(Txzorbl[4])
               #     print 'mv59'
                    intostr=intostr+"('"+str(sfile)+"','"+ str(line)+"','"+str(date)+"','" +str(houre)+"','"+ fen+"','"+ procs+"','"+chemin+"','"+str(ncl)+"', '','','"+str(action)+"','"+str(userid)+"','"+str(postepid)+"','"+str(poste['ADMINID'])+"');"
                    inscript=True
               #     print 'mv510'
             #   print 'minuteviwe6'
                if str(Txzorbl[2])in ["Created","Deleted","Updated","Renamed from something","Renamed to something"]:
               #     print 'inT'
                    chemin=Txzorbl[4]
                    action=Txzorbl[2]
                    line=Txzorbl[0]
                    userid=unchain(Txzorbl[6])
                    postepid=unchain(Txzorbl[7])
                    ncl=unchain(Txzorbl[3])
                    procs=chain(unchain(Txzorbl[5]))
                    
                    formatFanal()
                    if analyse==True:
                        analyseFichier(chemin)
                    chemin=chain(unchain(Txzorbl[4]))
                    fen=chemin
                    intostr=intostr+"('"+str(sfile)+"','"+ line+"','"+ date+"','" +houre+"','"+ fen+"','"+ procs+"','"+chemin+"','"+str(ncl)+"','"+fanal['client']+"','"+fanal['prestation']+"','"+str(action)+"','"+userid+"','"+postepid+"','"+poste["ADMINID"]+"');"    
                    inscript=True
                   # print 'good'
            #    print 'miuteview7'
                if inscript==True:
##                    conn_string = "host='"+str(users['serverip'])+"' dbname='chronos-monitor.com' user='chronos' password='gortex855'"
##                    conn = psycopg2.connect(conn_string)
##                    conn.set_client_encoding('UTF8')
##                    curs = conn.cursor()
##                    presult=curs.execute("SELECT action FROM logview WHERE userid='"+userid+"';")
##                    rresult=curs.fetchone()
##                    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)+"',posteid='"+str(poste['PID'])+"',final_userid='"+poste['ADMINID']+"' WHERE userid='"+str(userid)+"';"
                    result=cursex.execute(intostr)
                    connec.commit()
               #     print 'good'
##                    curs.close()
##                    conn.close()
            except:
                pass
             #   print 'error'
    class synchro(Thread):
        global invisible,syncrotip,lffile,lcfile,fline,cline,issyncro,pgb,anafennamin,anafennameq,anaprocspathin,anaprocspatheq,anaprocsnamin,anaprocsnameq,anaficpathin,anaficpatheq,anaficnamin,anaficnameq,fanal,analyse,mes,listeclient,listeactivite,slogpath,users
        def __init__(self):
            Thread.__init__(self)
            self.setDaemon(1)
            self.start()

        def chargeDonnees(self):
            global listeclient,listeactivite,users
            try:
                TchemFSF=oscurdir+os.sep+'wok'+os.sep+'conf'+os.sep+'local.gwh'
                isconfig=os.path.isfile(TchemFSF)
                if isconfig==True:
                    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"]=""
                    users['serverip']=""
                    users['serverdomain']=""
                    T=False
                    ip_enter=False
                    go_on=True
                    for char in lines:
                        if char=='\t':
                            p+=1
                            ip_enter=True
                            continue
                        if char=='\n':
                            break
                        if p==0 and l==0 and char in['i','p',':']:
                            ip_enter=True
                            go_on=False
                            continue
                            
                        if go_on==False:
                            if ip_enter==True and p==0 and l==0:
                                users['serverip']=users['serverip']+char
                            if p==1 and l==0:users['serverdomain']=users['serverdomain']+char
                            if p==2 and l==0:poste["PID"]=poste["PID"]+char
                            if p==3 and l==0:poste["ID"]=poste["ID"]+char
                            if p==4 and l==0:poste["posteNAME"]=poste["posteNAME"]+char
                            if p==5 and l==0:poste["Date"]=poste["Date"]+char
                            if p==6 and l==0:poste["GUID"]=poste["GUID"]+char
                            if p==7 and l==0:poste["ADMINID"]=poste["ADMINID"]+char
                        else:
                            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
                            users['serverip']='62.210.195.95'
                            users['serverdomain']='http://www.chronosmonitor.com'
                    if poste["ADMINID"]!="":    
                        conn_string = "host='"+str(users['serverip'])+"' dbname='chronos-monitor.com' user='chronos' password='gortex855'"
                        conn = psycopg2.connect(conn_string)
                        curs = conn.cursor()
                        result=curs.execute("SELECT nomsoc FROM clients WHERE idadmin='"+str(poste["ADMINID"])+"';" )
                        result=curs.fetchall()
                        x=0
                        if result:
                            for chain in result:
                                Tclient=""
                                for char in chain:
                                    Tclient=Tclient+str(char)
                                listeclient[x]=Tclient
                                listeclient['nombre']=x
                                x+=1
                        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
                        x=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[x,'prestation']=T0presta
                                listeactivite[x,'id']=T0idpresta
                                listeactivite['nombre']=x
                                x+=1
                                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[x,'prestation']=T1presta
                                        listeactivite[x,'id']=T1idpresta
                                        listeactivite['nombre']=x
                                        x+=1
                                        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[x,'prestation']=T2presta
                                                listeactivite[x,'id']=T2idpresta
                                                listeactivite['nombre']=x
                                                x+=1
                                                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="error run configuration wizard before"
                else:
                    message="error run configuration wizard before"
            except:
                message="internet connection required"


        def formatFanal(self):
            global fanal
            fanal['client']="None"
            fanal['prestation']="None"

        def analyseLibelle(libelle):
            global anafennamin,anafennameq,fanal,listeclient,listeactivite
            def unchain(nstring):
                try:
                    t=len(nstring)
                    result=""
                    string=nstring.decode('latin-1').encode('latin-1')
                    for x in range(0,t):
                        if string[x] in ['é','è','ê']:
                            result=result+'e'
                        elif string[x] in ['î','ï']:
                            result=result+'i'
                        elif string[x] in ['â','ä','à']:
                            result=result+'a'
                        elif string[x] in ['ô','ö']:
                            result=result+'o'
                        else:result=result+string[x]
                    return result
                except:
                    return nstring
            
            for x in range(1,anafennamin['count']+1):
                if unchain(anafennamin['contenu',x]).upper()==unchain(libelle).upper():
                    if anafennamin['client',x]!='undefined':
                        fanal['client']=anafennamin['client',x]
                    if anafennamin['prestation',x]!='non défini':
                        fanal['prestation']=anafennamin['prestationid',x]
                if anafennamin['contenu',x]=='Customer Name' and anafennamin['client',x]=='Customer mentioned':
                    for u in range(0,listeclient['nombre']):
                        if unchain(listeclient[u]).upper() ==unchain(libelle).upper():
                            fanal['client']=listeclient[u]
                if anafennamin['contenu',x]=='Service Name' and anafennamin['client',x]=='Service mentioned':
                    for u in range(0,listeactivite['nombre']):
                        if unchain(listeactivite[u,'prestation']).upper() ==unchain(libelle).upper():
                            fanal['prestation']=listeactivite[u,'id']

            for x in range(1,anafennameq['count']+1):
##                print unchain(anafennameq['contenu',x]).upper()
##                print unchain(libelle).upper()
                if unchain(anafennameq['contenu',x]).upper() in unchain(libelle).upper():
                    if anafennameq['client',x]!='undefined':
                        fanal['client']=anafennameq['client',x]
                    if anafennameq['prestation',x]!='undefined':
                        fanal['prestation']=anafennameq['prestationid',x]
                if anafennameq['contenu',x]=='Customer Name' and anafennameq['client',x]=='Customer mentioned':
                    for u in range(0,listeclient['nombre']):
                        if unchain(listeclient[u]).upper() in unchain(libelle).upper():
                            fanal['client']=listeclient[u]
                if anafennameq['contenu',x]=='Service Name' and anafennameq['client',x]=='Service mentioned':
                    for u in range(0,listeactivite['nombre']):
                        if unchain(listeactivite[u,'prestation']).upper() in unchain(libelle).upper():
                            fanal['prestation']=listeactivite[u,'id']
        def analyseProcessus(procs):
            global anaprocspathin,anaprocspatheq,anaprocsnamin,anaprocsnameq,fanal,listeclient,listeactivite
            def unchain(nstring):
                try:
                    t=len(nstring)
                    result=""
                    string=nstring.decode('latin-1').encode('latin-1')
                    for x in range(0,t):
                        if string[x] in ['é','è','ê']:
                            result=result+'e'
                        elif string[x] in ['î','ï']:
                            result=result+'i'
                        elif string[x] in ['â','ä','à']:
                            result=result+'a'
                        elif string[x] in ['ô','ö']:
                            result=result+'o'
                        else:result=result+string[x]
                    return result
                except:
                    return nstring
            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 unchain(anaprocspathin['contenu',x]).upper()==unchain(processpath).upper():
                    if anaprocspathin['client',x]!='undefined':
                        fanal['client']=anaprocspathin['client',x]
                    if anaprocspathin['prestation',x]!='undefined':
                        fanal['prestation']=anaprocspathin['prestationid',x]
                if anaprocspathin['contenu',x]=='Customer Name' and anaprocspathin['client',x]=='Customer mentioned':
                    for u in range(0,listeclient['nombre']):
                        if unchain(processpath).upper()==unchain(listeclient[u]).upper():
                            fanal['client']=listeclient[u]
                if anaprocspathin['contenu',x]=='Service Name' and anaprocspathin['client',x]=='Service mentioned':
                    for u in range(0,listeactivite['nombre']):
                        if unchain(processpath).upper()==unchain(listeactivite[u,'prestation']).upper():
                            fanal['prestation']=listeactivite[u,'id']
            for x in range(1,anaprocspatheq['count']+1):
                if unchain(anaprocspatheq['contenu',x]).upper() in unchain(processpath).upper():
                    if anaprocspatheq['client',x]!='undefined':
                        fanal['client']=anaprocspatheq['client',x]
                    if anaprocspatheq['prestation',x]!='non défini':
                        fanal['prestation']=anaprocspatheq['prestationid',x]
                if anaprocspatheq['contenu',x]=='Customer Name' and anaprocspatheq['client',x]=='Customer mentioned':
                    for u in range(0,listeclient['nombre']):
                        if unchain(listeclient[u]).upper() in unchain(processpath).upper():
                            fanal['client']=listeclient[u]
                if anaprocspatheq['contenu',x]=='Service Name' and anaprocspatheq['client',x]=='Service mentioned':
                    for u in range(0,listeactivite['nombre']):
                        if unchain(listeactivite[u,'prestation']).upper() in unchain(processpath).upper():
                            fanal['prestation']=listeactivite[u,'id']
            for x in range(1,anaprocsnamin['count']+1):
                if unchain(anaprocsnamin['contenu',x]).upper()==unchain(processfile).upper():
                    if anaprocsnamin['client',x]!='undefined':
                        fanal['client']=anaprocsnamin['client',x]
                    if anaprocsnamin['prestation',x]!='undefined':
                        fanal['prestation']=anaprocsnamin['prestationid',x]
                if anaprocsnamin['contenu',x]=='Customer Name' and anaprocsnamin['client',x]=='Customer mentioned':
                    for u in range(0,listeclient['nombre']):
                        if unchain(listeclient[u]).upper() ==unchain(processfile).upper():
                            fanal['client']=listeclient[u]
                if anaprocsnamin['contenu',x]=='Service Name' and anaprocsnamin['client',x]=='Service mentioned':
                    for u in range(0,listeactivite['nombre']):
                        if unchain(listeactivite[u,'prestation']).upper() == unchain(processfile).upper():
                            fanal['prestation']=listeactivite[u,'id']
            for x in range(1,anaprocsnameq['count']+1):
                if unchain(anaprocsnameq['contenu',x]).upper() in unchain(processfile).upper():
                    if anaprocsnameq['client',x]!='undefined':
                        fanal['client']=anaprocsnameq['client',x]
                    if anaprocsnameq['prestation',x]!='non défini':
                        fanal['prestation']=anaprocsnameq['prestationid',x]
                if anaprocsnameq['contenu',x]=='Customer Name' and anaprocsnameq['client',x]=='Customer mentioned':
                    for u in range(0,listeclient['nombre']):
                        if unchain(listeclient[u]).upper() in unchain(processfile).upper():
                            fanal['client']=listeclient[u]
                if anaprocsnameq['contenu',x]=='Service Name' and anaprocsnameq['client',x]=='Service mentioned':
                    for u in range(0,listeactivite['nombre']):
                        if unchain(listeactivite[u,'prestation']).upper() in unchain(processfile).upper():
                            fanal['prestation']=listeactivite[u,'id']
        def analyseFichier(fichier):
            global anaficpathin,anaficpatheq,anaficnamin,anaficnameq,fanal,listeclient,listeactivite
            def unchain(nstring):
                try:
                    t=len(nstring)
                    result=""
                    string=nstring.decode('latin-1').encode('latin-1')
                    for x in range(0,t):
                        if string[x] in ['é','è','ê']:
                            result=result+'e'
                        elif string[x] in ['î','ï']:
                            result=result+'i'
                        elif string[x] in ['â','ä','à']:
                            result=result+'a'
                        elif string[x] in ['ô','ö']:
                            result=result+'o'
                        else:result=result+string[x]
                    return result
                except:
                    return nstring
            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 unchain(anaficpathin['contenu',x]).upper()==unchain(filepath).upper():
                    if anaficpathin['client',x]!='undefined':
                        fanal['client']=anaficpathin['client',x]
                    if anaficpathin['prestation',x]!='undefined':
                        fanal['prestation']=anaficpathin['prestationid',x]
                if anaficpathin['contenu',x]=='Customer Name' and anaficpathin['client',x]=='Customer mentioned':
                    for u in range(0,listeclient['nombre']):
                        if unchain(listeclient[u]).upper() == unchain(filepath).upper():
                            fanal['client']=listeclient[u]
                if anaficpathin['contenu',x]=='Service Name' and anaficpathin['client',x]=='Service mentioned':
                    for u in range(0,listeactivite['nombre']):
                        if unchain(listeactivite[u,'prestation']).upper() == unchain(filepath).upper():
                            fanal['prestation']=listeactivite[u,'id']
            for x in range(1,anaficpatheq['count']+1):
                if unchain(anaficpatheq['contenu',x]).upper() in unchain(filepath).upper():
                    if anaficpatheq['client',x]!='undefined':
                        fanal['client']=anaficpatheq['client',x]
                    if anaficpatheq['prestation',x]!='non défini':
                        fanal['prestation']=anaficpatheq['prestationid',x]
                if anaficpatheq['contenu',x]=='Customer Name' and anaficpatheq['client',x]=='Customer mentioned':
                    for u in range(0,listeclient['nombre']):
                        if unchain(listeclient[u]).upper() in unchain(filepath).upper():
                            fanal['client']=listeclient[u]
                if anaficpatheq['contenu',x]=='Service Name' and anaficpatheq['client',x]=='Service mentioned':
                    for u in range(0,listeactivite['nombre']):
                        if unchain(listeactivite[u,'prestation']).upper() in unchain(filepath).upper():
                            fanal['prestation']=listeactivite[u,'id']
            for x in range(1,anaficnamin['count']+1):
                if unchain(anaficnamin['contenu',x]).upper()==unchain(filefile).upper():
                    if anaficnamin['client',x]!='undefined':
                        fanal['client']=anaficnamin['client',x]
                    if anaficnamin['prestation',x]!='undefined':
                        fanal['prestation']=anaficnamin['prestationid',x]
                if anaficnamin['contenu',x]=='Customer Name' and anaficnamin['client',x]=='Customer mentioned':
                    for u in range(0,listeclient['nombre']):
                        if unchain(listeclient[u]).upper() == unchain(filefile).upper():
                            fanal['client']=listeclient[u]
                if anaficnamin['contenu',x]=='Service Name' and anaficnamin['client',x]=='Service mentioned':
                    for u in range(0,listeactivite['nombre']):
                        if unchain(listeactivite[u,'prestation']).upper() in unchain(filefile).upper():
                            fanal['prestation']=listeactivite[u,'id']
            for x in range(1,anaficnameq['count']+1):
                if unchain(anaficnameq['contenu',x]).upper() == unchain(filefile).upper():
                    if anaficnameq['client',x]!='undefined':
                        fanal['client']=anaficnameq['client',x]
                    if anaficnameq['prestation',x]!='undefined':
                        fanal['prestation']=anaficnameq['prestationid',x]
                if anaficnameq['contenu',x]=='Customer Name' and anaficnameq['client',x]=='Customer mentioned':
                    for u in range(0,listeclient['nombre']):
                        if unchain(listeclient[u]).upper() in unchain(filefile).upper():
                            fanal['client']=listeclient[u]
                if anaficnameq['contenu',x]=='Service Name' and anaficnameq['client',x]=='Service mentioned':
                    for x in range(0,listeactivite['nombre']):
                        if unchain(listeactivite[u,'prestation']).upper() in unchain(filefile).upper():
                            fanal['prestation']=listeactivite[u,'id']


        def run(self):
            global fanal,analyse,mes,pgb,issyncro,lffile,lcfile,fline,cline,users
            if analyse==True:
                self.chargeDonnees()
            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
            def intFormat(string):
                for char in string:
                    if char not in['0','1','2','3','4','5','6','7','8','9']:
                        return '0'
                return string
                #self.dc.DrawBitmap(self.syncf, 51, 168, True)

            #self.dc.DrawBitmap(self.onsync, 49, 168, True)
            issyncro=True
            conn_string = "host='"+str(users['serverip'])+"' dbname='chronos-monitor.com' user='chronos' password='gortex855'"
            conn = psycopg2.connect(conn_string)
            conn.set_client_encoding('UTF8')
            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]
            u=0
            maj={}
            full=False

            cfic={}
            ffic={}
            i=0
            z=0
            encdir=slogpath
            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]
                                cfic[z,'name']=condfichier
                                cfic[z,'type']="condensed"
                                z=z+1
##                                print 'condensed'+str(maj['fichier',up])
##                                print 'full'+str(maj['fichier',u])
                            elif str(chem[xil-4:xil])==".gwh":
                                ffic[i,'name']=fichier
                                ffic[i,'type']="full"
                                i=i+1
            pith=ffic[0,'name']
            for zi in range(0,i+1):
                try:
                    lcd=len(pith)
                    lfc=len(ffic[zi,'name'])
                    namor=pith[0:8]
                    xnamur=ffic[zi,'name']
                    namur=xnamur[0:8]
                    xna=pith[8:lcd]
                    xno=xnamur[8:lfc]
                    if xna=='':xna=0
                    if xno=='':xno=0
                    if int(namor) < int(namur):
                        continue
                    if int(namor) == int(namur)and int(xna)< int(xno):
                        continue
                    if str(namor)==str(namur)and int(xna)== int(xno):
                        continue
                    if int(namor) > int(namur):
                        pith=ffic[zi,'name']
                    if str(namor)==str(namur)and int(xna)> int(xno):
                        pith=ffic[zi,'name']
                except:
                    pass
            ffic[0,'name']=pith 
            tith=cfic[0,'name']
            for zi in range(0,z+1):
                try:
                    lcd=len(tith)
                    lfc=len(cfic[zi,'name'])
                    namor=tith[0:8]
                    xnamur=cfic[zi,'name']
                    namur=xnamur[0:8]
                    xna=tith[8:lcd]
                    xno=xnamur[8:lfc]
                    if xna=='':xna=0
                    if xno=='':xno=0
                    if int(namor) < int(namur):
                        continue
                    if int(namor) == int(namur)and int(xna)< int(xno):
                        continue
                    if str(namor)==str(namur)and int(xna)== int(xno):
                        continue
                    if int(namor) > int(namur):
                        tith=cfic[zi,'name']
                    if str(namor)==str(namur)and int(xna)> int(xno):
                        tith=cfic[zi,'name']
                except:
                    pass
            cfic[0,'name']=tith  


            
            if str(lffile)=='' or syncrotip=='cont':
                try:
                    intostr="SELECT file, line FROM logfull where posteid='"+poste["ID"]+"'  ORDER BY id ASC;"
                    presult=curs.execute(str(intostr))
                    presult=curs.fetchall()
                    p=0
                    if presult:
                        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
                    else:
                        maj['fichier',u]=ffic[0,'name']
                        maj['line',u]='0'
                        maj['type',u]="full"
                        full=True
                except:
                    mes="internet indisponible"
                    if invisible==False:
                        self.dc.message.SetValue(unicode(mes))
                    return
            else:
                    maj['fichier',u]=lffile
                    maj['line',u]=fline
                    maj['type',u]="full"
                    full=True
            if str(maj['fichier',u])=='0' and str(maj['line',u])=='0':
                try:
                    intostr="SELECT nomfichier, line FROM logmaj where posteid='"+poste["ID"]+"' and type='full' ORDER BY datemaj ASC;"
                    presult=curs.execute(str(intostr))
                    presult=curs.fetchall()
                    u=0
                    p=0
                    full=False
                    if presult:
                        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
                    else:
                        maj['fichier',u]=ffic[0,'name']
                        maj['line',u]='1'
                        maj['type',u]="full"
                        full=True
                except:
                    mes="internet indisponible"
                    if invisible==False:
                        self.dc.message.SetValue(unicode(mes))
                    return

##            print 'file-full :',maj['fichier',u]
##            print 'line-full :',maj['line',u]
            up=u+1
            cond=False
            ftinscript=False
            ctinscript=False
            if str(lcfile)=='' or syncrotip=='cont':
                pintostr="SELECT file, line FROM logcondensed where posteid='"+poste["ID"]+"' ORDER BY id ASC;"
                ppresult=curs.execute(str(pintostr))
                ppresult=curs.fetchall()
                po=0
                if ppresult:
                    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
                else:
                    maj['fichier',up]=cfic[0,'name']
                    maj['line',up]='0'
                    maj['type',up]="condensed"
                    cond=True
            else:
                    maj['fichier',up]=lcfile
                    maj['line',up]=cline
                    maj['type',up]="condensed"
                    cond=True

            if str(maj['fichier',up])=='0' and str(maj['line',up])=='0':               
                pintostr="SELECT nomfichier, line FROM logmaj where posteid='"+poste["ID"]+"' and type='condensed' ORDER BY datemaj ASC;"
                ppresult=curs.execute(str(pintostr))
                ppresult=curs.fetchall()
                up=u
                po=0
                cond=False
                ftinscript=False
                ctinscript=False
                if ppresult:
                    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
                else:
                    maj['fichier',up]=cfic[0,'name']
                    maj['line',up]='0'
                    maj['type',up]="condensed"
                    cond=True

##            print 'file-condensed :',maj['fichier',up]
##            print 'line-condensed :',maj['line',up]
            
            encdir=slogpath
            #self.dc.message.SetValue(unicode(mes)+"-")
            g=0
            try:
                pgb.Show()
            except:
                pass
            ligne={}
            xzorbl={}
            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]
                                dfic=condfichier
##                                print 'condensed'+str(maj['fichier',up])
##                                print 'full'+str(maj['fichier',u])
                                if cond==True:
                                    lcd=len(condfichier)
                                    lfc=len(maj['fichier',up])
                                    namor=condfichier[0:8]
                                    xnamur=maj['fichier',up]
                                    namur=xnamur[0:8]
                                    xna=condfichier[8:lcd]
                                    xno=xnamur[8:lfc]
                                    if xna=='':xna=0
                                    if xno=='':xno=0
##                                    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"
##                                    print str(namor) +':'+ str(namur)
##                                    print str(xna) +':'+ str(xno)
                                     
                                    if int(namor) < int(namur)and str(maj['type',up])=='condensed':
                                        continue
                                    if int(namor) == int(namur)and int(xna)< int(xno) and str(maj['type',up])=='condensed':
                                        continue
                                    if str(namor)==str(namur) and int(xna)== int(xno) and str(maj['type',up])=='condensed':
                                        tze=int(maj['line',up])+1
                                    if int(namor) > int(namur)and str(maj['type',up])=='condensed':
                                        tze=1
                                    if str(namor)==str(namur) and int(xna)> int(xno) and str(maj['type',up])=='condensed':
                                        tze=1
                                        
                            elif str(chem[xil-4:xil])==".gwh":
                                dfic=fichier
                                if full==True:
                                    lcd=len(fichier)
                                    lfc=len(maj['fichier',u])
                                    namor=fichier[0:8]
                                    xnamur=maj['fichier',u]
                                    namur=xnamur[0:8]
                                    xna=fichier[8:lcd]
                                    xno=xnamur[8:lfc]
                                    if xna=='':xna=0
                                    if xno=='':xno=0
##                                    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"
##                                    print str(namor) +':'+ str(namur)
##                                    print str(xna) +':'+ str(xno)
                                    if int(namor) < int(namur)and str(maj['type',u])=='full':
                                        continue
                                    if int(namor) == int(namur)and int(xna)< int(xno) and str(maj['type',u])=='full':
                                        continue
                                    if str(namor)==str(namur)and int(xna)== int(xno) and str(maj['type',u])=='full':
                                        tze=int(maj['line',u])+1
                                    if int(namor) > int(namur)and str(maj['type',u])=='full':
                                        tze=1
                                    if str(namor)==str(namur)and int(xna)> int(xno) and str(maj['type',u])=='full':
                                        tze=1


                            drink=FicExport(chemr,fic)
                            #print 'drink=',str(drink)
                            try:
                                FXTCstring=xml.dom.minidom.parseString(drink)
                            except:
                                print ('file error: '+str(fic))
                                continue
                            fstr=""
                            lines = FXTCstring.getElementsByTagName('PrsP')
                            x=0
                            lignes={}
                            for line in lines:
                                lignes[x]=line.getAttribute('ReportLine')
                                x+=1
                                #
                                                        
                            z=0
                            p=0
    ##                        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
                            if xil>13 and chem[xil-13:xil]=="condensed.gwh":
                                tip="condensed"
                                ligne['condensed','tze']=tze
                                ligne['condensed']=dfic
                            else:
                                tip="full"
                                ligne['full','tze']=tze
                                ligne['full']=dfic
                            for r in range(0,t):
                                line = lignes[r]
                                z=r
                                p=0
                                xzorbl[g,p,z]=""
                                ln=len(line)
                                ligne[g,'tip']=tip
                                ligne[g,'tze']=tze
                                ligne[g,'z']=z
                                ligne[g,'fichier']=dfic
                                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[g,p,z]=""
                                    else:

                                        xzorbl[g,p,z]=xzorbl[g,p,z]+char
                                g+=1
##                            print 'fichier: ' + str(dfic)
##                            print 'tze: '+ str(tze)
##                            print 'tip: '+ str(tip)
##                            print 'g:'+str(g)
                                
            tg=g-1
            try:
                pgb.SetRange(tg)
            except:
                pass
            #print 'xu'
            for u in range(1,g):
                try:
                    pgb.SetValue(u)
                except:
                    pass
                #print 'xo'
                ses=0
                fic=0
                proc=0
                procv=0
                winv=0
                fen=""
                procs=""
                chemin=""
                date=""
                houre=""
                o=0
                p=0
                q=0
                try:
                    for x in range(0,ligne[u,'z']):
                        for t in range(0,i):
                            try:
                                xzorbl[u,t,x]=xzorbl[u,t,x].strip()
                                xzorbl[u,t,x]=xzorbl[u,t,x].strip("\r\n")
                            except:
                                pass
                except:
                    pass
                try:
                    if ligne[u,'tip']=="condensed":
                        tip="condensed"
                        intostr="""INSERT INTO logcondensed (file, line, date, heure, nomfenetre, processus, chemin, clicks, client,activite,action,userid,posteid,final_userid) VALUES """

                    else:
                        tip="full"
                        intostr="""INSERT INTO logfull (file, line, date, heure, nomfenetre, processus, chemin, clicks, client,activite,action,userid,posteid,final_userid) VALUES """

                except:
                    continue
                inscript=False
##                print 'file=',ligne[u,'fichier']
##                print 'tip=',ligne[u,'tip']
##                print 'tze=',ligne[u,'tze']
##                print 'z=',ligne[u,'z']
                for x in range(ligne[u,'tze'],ligne[u,'z']+1):
                    #for t in range(0,i):
                    #try:
                    
                    try:
                        hour=xzorbl[u,1,x]
                    except:
                        continue
                    dateprem=hour[0:8]
                    date='20'+dateprem[6:8]+'/'+dateprem[0:2]+'/'+dateprem[3:5]
                    houre=hour[9:18]
                    datour=str(xzorbl[u,1,x]) 
                    t=len(intostr)
                    ll=intFormat(xzorbl[u,0,x])
                    if ligne[u,'tip']=="condensed":
                        ligne['condensed','ll']=ll
                        xfile=ligne[u,'fichier']
                    elif ligne[u,'tip']=="full":
                        ligne['full','ll']=ll
                        xfile=ligne[u,'fichier']
                    chemin="None"
                    procs="None"
                    fen="None"
                    if str(xzorbl[u,2,x])=='user_begin':
                        if inscript==True:intostr=intostr+",('"+str(xfile)+"','"+ str(ll)+"','"+date+"','"+ houre+"','"+ fen+"','"+ procs+"','"+chemin + "', '0', '','','debut session','"+xzorbl[u,3,x]+"','"+xzorbl[u,5,x]+"','"+poste["ADMINID"]+"')"
                        else:intostr=intostr+"('"+str(xfile)+"','"+ str(ll)+"','"+date+"','"+ houre+"','"+ fen+"','"+ procs+"','"+chemin + "', '0', '','','debut session','"+xzorbl[u,3,x]+"','"+xzorbl[u,5,x]+"','"+poste["ADMINID"]+"')"
                        inscript=True
                    elif str(xzorbl[u,2,x])=='widget_stop':
                        if inscript==True:intostr=intostr+",('"+str(xfile)+"','"+ str(ll)+"','"+date+"','"+ houre+"','"+ fen+"','"+ procs+"','"+chemin+"', '0', '','','fin session','"+xzorbl[u,3,x]+"','"+xzorbl[u,5,x]+"','"+poste["ADMINID"]+"')"
                        else:intostr=intostr+"('"+str(xfile)+"','"+ str(ll)+"','"+date+"','"+ houre+"','"+ fen+"','"+ procs+"','"+chemin+"', '0', '','','fin session','"+xzorbl[u,3,x]+"','"+xzorbl[u,5,x]+"','"+poste["ADMINID"]+"')"
                        inscript=True
                        ses+=1
                    elif str(xzorbl[u,2,x])in ["Created","Deleted","Updated","Renamed from something","Renamed to something"]:
                        chemin=xzorbl[u,4,x]
                        userid=intFormat(tunchain(xzorbl[u,6,x]))
                        postepid=intFormat(tunchain(xzorbl[u,7,x]))
                        ncl= intFormat(unchain(xzorbl[u,3,x]))
                        procs=chain(unchain(xzorbl[u,5,x]))
                        
                        self.formatFanal()
                        if analyse==True:
                            self.analyseFichier(chemin)
                        chemin=chain(unchain(xzorbl[u,4,x]))
                        fen=chain(unchain(xzorbl[u,4,x]))
                        if inscript==True:intostr=intostr+",('"+str(xfile)+"','"+ str(ll)+"','"+ date+"','" +houre+"','"+ fen+"','"+ procs+"','"+chemin+"','"+str(ncl)+"','"+fanal['client']+"','"+fanal['prestation']+"','"+xzorbl[u,2,x]+"','"+userid+"','"+postepid+"','"+poste["ADMINID"]+"')"    
                        else:intostr=intostr+"('"+str(xfile)+"','"+ str(ll)+"','"+ date+"','" +houre+"','"+ fen+"','"+ procs+"','"+chemin+"','"+str(ncl)+"','"+fanal['client']+"','"+fanal['prestation']+"','"+xzorbl[u,2,x]+"','"+userid+"','"+postepid+"','"+poste["ADMINID"]+"')"    
                        inscript=True
                    elif str(xzorbl[u,2,x])=='minute_maid':
                        ncl= intFormat(unchain(xzorbl[u,3,x]))
                        chemin="None"
                        self.formatFanal()
                        if analyse==True:
                            self.analyseProcessus(xzorbl[u,5,x])
                            self.analyseLibelle(xzorbl[u,4,x])
                        procs=chain(unchain(xzorbl[u,5,x]))
                        fen=chain(unchain(xzorbl[u,4,x]))
                        userid=intFormat(tunchain(xzorbl[u,6,x]))
                        postepid=intFormat(tunchain(xzorbl[u,7,x]))
                        if inscript==True:intostr=intostr+",('"+str(xfile)+"','"+ str(ll)+"','"+date+"','" +houre+"','"+ fen+"','"+ procs+"','"+chemin+"', '"+str(ncl)+"','"+fanal['client']+"','"+fanal['prestation']+"','log','"+userid+"','"+postepid+"','"+poste["ADMINID"]+"')"
                        else:intostr=intostr+"('"+str(xfile)+"','"+ str(ll)+"','"+date+"','" +houre+"','"+ fen+"','"+ procs+"','"+chemin+"', '"+str(ncl)+"','"+fanal['client']+"','"+fanal['prestation']+"','log','"+userid+"','"+postepid+"','"+poste["ADMINID"]+"')"
                        inscript=True
                    elif str(xzorbl[u,2,x])=='window_change-mouse':
                        Trmbl=False
                        chemin="None"
                        self.formatFanal()
                        if analyse==True:
                            self.analyseProcessus(xzorbl[u,5,x])
                            self.analyseLibelle(xzorbl[u,4,x])
                        try:
                            userid=intFormat(tunchain(xzorbl[u,6,x]))
                        except:
                            userid=0
                        try:
                            postepid=intFormat(poste["ID"])
                        except:
                            postepid=intFormat(poste['PID'])
                        try:
                            procs=chain(unchain(xzorbl[u,5,x]))
                        except:
                            procs="None"
                        try:
                            ncl=0
                            fen=chain(unchain(xzorbl[u,4,x]))
                        except:
                            fen="None"
                        try:
                            ncl=intFormat(chain(unchain(xzorbl[u,3,x])))
                        except:
                            ncl=0
                        if inscript==True:intostr=intostr+",('"+str(xfile)+"','"+ str(ll)+"','"+str(date)+"','" +str(houre)+"','"+ fen+"','"+ procs+"','"+chemin+"','"+str(ncl)+"','"+fanal['client']+"','"+fanal['prestation']+"','log','"+userid+"','"+postepid+"','"+poste["ADMINID"]+"')"
                        else:intostr=intostr+"('"+str(xfile)+"','"+ str(ll)+"','"+str(date)+"','" +str(houre)+"','"+ fen+"','"+ procs+"','"+chemin+"','"+str(ncl)+"','"+fanal['client']+"','"+fanal['prestation']+"','log','"+userid+"','"+postepid+"','"+poste["ADMINID"]+"')"
                        inscript=True
                    #print 'xzorbl :'+str(xzorbl[u,2,x])
##                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)
                #print 'inscript :',inscript
                if inscript:
                    try:
                        result=curs.execute(intostr)
                        conn.commit()
                        #print intostr
                        intostr=""
##                        if ligne[u,'tip']=="full":ftinscript=True
##                        elif ligne[u,'tip']=="condensed":ctinscript=True
                        if ligne[u,'tip']=="condensed":
                            lcfile=ligne[u,'fichier']
                            cline=ligne['condensed','ll']
                        elif ligne[u,'tip']=="full":
                            fline=ligne['full','ll']
                            lffile=ligne[u,'fichier']
                    except:
                        pass
                        #exceptionType, exceptionValue, exceptionTraceback = sys.exc_info()
                        #print "Database connection failed!\n ->%s" % (exceptionValue)
                        #print "Probably internet connection" 
##            if ftinscript:
##                try:
##                    tintostr="""INSERT INTO logmaj (datemaj, nomfichier, type, start,line, posteid, userid)
##                            VALUES
##                            """
##                    tintostr=str(tintostr)+"('now()','"+str(ligne['full'])+"','full','"+str(ligne['full','tze'])+"','"+str(ligne['full','ll'])+"','"+str(poste["ID"])+"','"+str(user["ID",to])+"');"
##                    result=curs.execute(str(tintostr))
##                    conn.commit()
##    ##                print str(tintostr)
##                    #print 'logmaj tze full '+str(ligne['full','tze'])
##                    tintostr=""
##                except:
##                    exceptionType, exceptionValue, exceptionTraceback = sys.exc_info()
##                    print "logmaj full Database connection failed!\n ->%s" % (exceptionValue)
##            if ctinscript:
##                try:
##                    tintostr="""INSERT INTO logmaj (datemaj, nomfichier, type, start,line, posteid, userid)
##                            VALUES
##                            """
##                    tintostr=str(tintostr)+"('now()','"+str(ligne['condensed'])+"','condensed','"+str(ligne['condensed','tze'])+"','"+str(ligne['condensed','ll'])+"','"+str(poste["ID"])+"','"+str(user["ID",to])+"');"
##                    #print str(tintostr)
##                    #print intostr
##                    #print 'logmaj tze condensed '+ str(ligne['condensed','tze'])
##                    result=curs.execute(str(tintostr))
##                    conn.commit()
##                    tintostr=""
##                    #self.dc.message.SetValue(unicode(mes)+u'-synchronisé')
##                except:
##                    exceptionType, exceptionValue, exceptionTraceback = sys.exc_info()
##                    print "logmaj condensed Database connection failed!\n ->%s" % (exceptionValue)
##                    print repr(tintostr)
##            print 'ctinscript '+ str(ctinscript)
##            print 'ftinscript '+ str(ftinscript)
                
            curs.close()
            conn.close()
            pgb.Hide()
            issyncro=False






    def OnLeftDown(self, event):
        global observer,stream,cocoastart,invisible,hmh,conex,cursex,connec,ffile,syncrotip,issyncro,line1,line2,line3,dusers,jak,to,fl,cl,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,ssyncro,dossier,watcher,users,to
        class OnMouseEventAfter(Thread):
            global ffile,dusers,jak,to,fl,cl,resac,win,nombrecliq,processactif,user,poste,prs,mes,rept,XTstring,syncrotip,users

            def __init__(self,event):
                Thread.__init__(self)
                self.setDaemon(1)
                self.event=event
                self.start()
            def TSave(self):
                global XTstring
                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 Twrite(self,string):
                global rept,XTstring,fl,syncrotip
                try:
                    racine=XTstring.documentElement
                    element =XTstring.createElement("PrsP")
                    element.setAttribute('ReportLine',string)
                    racine.appendChild(element)
                    self.TSave()
                finally:
                    if syncrotip=='cont':
                        Widget.minuteView(string,'full')
                      #  print 'appel onleftdown'
            def run(self):
                global dusers,jak,to,fl,cl,resac,win,nombrecliq,processactif,user,poste,prs,mes,syncrotip
                def unchain(string):
                    result=""
                    if string:
                        x=len(string)
                        if int(x)>100:x=100
                        for x in range(0,x):
                            if string[x] in ["'",'"']:
                                result=result+' '
                            elif 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=self.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
##                try:
##                    hwnd = win32gui.GetForegroundWindow()
##                    # we want the desktop window
##                    objid = pyAA.Constants.OBJID_WINDOW
##                    # get the object
##                    #ao = pyAA.AccessibleObjectFromPoint(event.Position)
##                    ao = pyAA.AccessibleObjectFromWindow(hwnd, objid)
##                    pr= ao.GetProcessAndThreadID()
##                    p = psutil.Process(pr[0])
##                    processactif=p.exe
##    ##                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
##                except:
##                    processactif="None"
                try:
                    syscod=sys.getdefaultencoding()
                    tprocess=processactif.decode(syscod)
                except:
                    try:
                        tprocess=processactif.decode('utf-8')
                    except:
                        try:
                            tprocess=processactif.decode(encodings["Principal"])
                            #tprocess=unchain(processactif)
                        except:
                            try:
                                tprocess=processactif.decode(encodings["Deuxieme"])
                            except:
                                try:
                                    tprocess=processactif.decode(encodings["Troisieme"])
                                except:
                                    try:
                                        tprocess=processactif.decode(encodings["Quatrieme"])
                                    except:
                                        tprocess='None'
                try:
                    fen=unchain(self.event.WindowName)
                    fen=fen.decode(encodings["Principal"])
                    #tprocess=unchain(processactif)
                except:
                    try:
                        fen=fen.decode(encodings["Deuxieme"])
                    except:
                        try:
                            fen=fen.decode(encodings["Troisieme"])
                        except:
                            try:
                                fen=fen.decode(encodings["Quatrieme"])
                            except:
                                fen=''
##                    fen=unchain(self.event.WindowName).decode('latin-1')
##                    if fen=="":
##                        try:
##                            fen=unchain(ao.Name).decode('latin-1')
##                        except:
##                            fen="None"
##                except:
##                    try:
##                        fen=unchain(ao.Name).decode('latin-1')
##                    except:
##                        try:
##                            fen=unchain(ao.Name)
##                        except:
##                            fen="None"
                if fen=="":
                    try:
                        fen='none'#unchain(ao.Name)
                        syscod=sys.getdefaultencoding()
                        fen=fen.decode(syscod)
                    except:
                        try:
                            fen=fen.decode(encodings["Principal"])
                            #tprocess=unchain(processactif)
                        except:
                            try:
                                fen=fen.decode(encodings["Deuxieme"])
                            except:
                                try:
                                    fen=fen.decode(encodings["Troisieme"])
                                except:
                                    try:
                                        fen=fen.decode(encodings["Quatrieme"])
                                    except:
                                        fen="None"
                if tprocess=="":tprocess="None"
                        
                resac=str(fl)+'#'+str(timec)+'#'+'window_change-mouse'+'#'+str(nombrecliq)+'#'+fen+'#'+unchain(tprocess)+'#'+str(user["ID",int(to)])+'#'+str(poste["PID"])+'\n'
                fl+=1
                self.Twrite(resac)
                return True
#        def OnMouseEvent(event):
#            wx.CallAfter(OnMouseEventAfter, event)
#            return True
#        def NoEvent(event):
#            return True
        pos = event.GetPosition()
        if self.crossoverRegion.Contains(pos):
            for x in range(458,476):
                try:
                    frame=wx.FindWindowById(x)
                    if frame.IsShown():
                        frame.Close()
                except:
                    pass
            if start ==True:
##                try:
##                    hm.UnhookMouse()
##                    #ctypes.windll.user32.PostQuitMessage(0)
##                    #del hm
##                    hmh=False
##                except:
##                    hmh=True
                try:
                    cursex.close()
                    connec.close()
                except:
                    pass

                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)
                #sc.cancel()
                try:
                    observer.unschedule(stream)
                    observer.stop()
                except:
                    pass
                cocoastart=False
                #minuteView(resac)
                if syncrotip=='cont' and conex==True:
                    self.minuteView(resac,'full')
                    self.minuteView(resac,'condensed')
                    try:
                        cursex.close()
                        connec.close()
                    except:
                        pass
                timer.Stop()
                #timerF.Stop()
                #timerD.Stop()
            #self.Close()
            #app.Destroy()
            #app.quit()
            os._exit(0)
            #pid=os.getpid()
            #os.kill(pid, signal.SIGKILL)
        elif self.reduceRegion.Contains(pos):
            for x in range(458,472):
                try:
                    frame=wx.FindWindowById(x)
                    if frame.IsShown():
                        frame.Hide()
                except:
                    pass
            self.Hide()
        elif self.syncRegion.Contains(pos):
            wx.BufferedDC(wx.ClientDC(self),self.onsync)
            if start ==True:
                if issyncro==True:
                    if invisible==False:
                        self.dc.message.SetValue(unicode('synchronisation en cours'))
                elif syncrotip=='cont':
                    if conex==False:
                        try:
                            self.synchro()
                        finally:
                            conex=True
                    elif conex==True:
                        if invisible==False:
                            self.dc.message.SetValue(unicode('la synchronisation est continue'))
                else:
                    self.synchro()
            else:
                mes="You have to log first"
            
        elif self.loginRegion.Contains(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'
            isconfig=os.path.isfile(TchemFSF)
            if isconfig==True:
                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
                ip_enter=False
                go_on=True
                users['serverip']=""
                users['serverdomain']=""
                for char in lines:
                    if char=='\t':
                        p+=1
                        ip_enter=True
                        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 and char in['i','p',':']:
                        ip_enter=True
                        go_on=False
                        continue
                    if go_on==False:
                        if ip_enter==True and p==0 and l==0:
                            users['serverip']=users['serverip']+char
                        if p==1 and l==0:users['serverdomain']=users['serverdomain']+char
                        if p==2 and l==0:poste["PID"]=poste["PID"]+char
                        if p==3 and l==0:poste["ID"]=poste["ID"]+char
                        if p==4 and l==0:poste["posteNAME"]=poste["posteNAME"]+char
                        if p==5 and l==0:poste["Date"]=poste["Date"]+char
                        if p==6 and l==0:poste["GUID"]=poste["GUID"]+char
                        if p==7 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
                    else:
                        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
                        users['serverip']='62.210.195.95'
                        users['serverdomain']='http://www.chronosmonitor.com'
    ##            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["ID"]
                            poste["PID"]=poste["ID"]
                            user["nombre"]=l
                            to=int(x)
                            found=True
                            #print 'gagne'
                if found==False or str(found) == "not":
                    if found==False:
                        mes='login error'
                        if invisible==False:
                            self.dc.message.SetValue(unicode('login error'))
                    elif str(found)=="not":
                        mes='enter password'
                        if invisible==False:
                            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='"+str(users['serverip'])+"' dbname='chronos-monitor.com' user='chronos' password='gortex855'"
                        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
                            keyvalue="mackey"
##                            try:
##                                regroot=_winreg.HKEY_LOCAL_MACHINE
##                                hKey=_winreg.OpenKey(regroot,"SOFTWARE\Microsoft\Cryptography",0,_winreg.KEY_READ)
##                                keyvalue, type=_winreg.QueryValueEx(hKey, "MachineGuid")
##                            except:
##                                keyvalue="undefined"
                            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='error opening local.gwg'
                                    
                                    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+'-encryption error'
                                    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)
##                                    if hmh==False:
##                                        try:
##                                            hm.MouseAllButtonsDown = OnMouseEvent
##                                            #hm.MouseMove = NoEvent
##                                            #hm.MouseLeftDown = OnMouseEvent
##                                           
##                                            #hm.MouseRightDown = OnMouseEvent
##                                            # set the hook user["ID",to]
##                                            hm.HookMouse()
##                                            #pythoncom.PumpMessages
##                                        finally:
##                                            hmh=True
                                        #print ('tstart1')
                                        if cocoastart==False:
                                            #sc = SniffCocoa()
                                            #sc.run()
                                            cocoastart=True
                                        mes='-'+user["nom",to]+'-connected-'
                                        #self.dc.message.SetEditable(True)
                                        if invisible==False:
                                            self.dc.message.SetValue(unicode(mes))
                                        computer = None
                                        logType = "Security"
                                        verbose = 0
                                        #elf.dc.message.SetEditable(False)
                                        start=True
                                        if ssyncro==True:self.chargeDossier()
                                        timer.Start(milliseconds=60000, oneShot=False)
                                        #minuteView(resac)
                                        if syncrotip=='cont':
                                            try:
                                                conn_string = "host='"+str(users['serverip'])+"' dbname='chronos-monitor.com' user='chronos' password='gortex855'"
                                                connec = psycopg2.connect(conn_string)
                                                connec.set_client_encoding('UTF8')
                                                cursex = connec.cursor()
                                                self.minuteView(resac,'full')
                                                self.minuteView(resac,'condensed')
                                                conex=True
                                            except:
                                                mes="no internet, syncro off"
                                                if invisible==False:
                                                    self.dc.message.SetValue(unicode(mes))
                                                conex=False
                                                syncrotip='manu'
                                        if str(on_open)=="True" or on_open==True:
                                            #print '1245478'
                                            try:
                                                frame=wx.FindWindowById(444)
                                                if frame.IsShown():
                                                    frame.Hide()
                                                    #print '12457810'
                                                #else:
                                                    #print '12457814'
                                                #print '12457812'
                                            except:
                                                pass
                                            
                                        #timerF.Start(milliseconds=10000, oneShot=False)
                                else:

                                    line1="Licence is out-of-date."
                                    line2="Ask the renewal" 
                                    line3="to your administrator."
                                    try:
                                        dialogframe = wx.FindWindowById(465)
                                        dialogframe.Close()
                                        WizardEnd(None, 465, 'Chronos Monitor Configuration')            
                                    except:
                                        WizardEnd(None, 465, 'Chronos Monitor Configuration')
                            else:

                                line1="Licence is out-of-date."
                                line2="Ask the renewal" 
                                line3="to your administrator."
                                try:
                                    dialogframe = wx.FindWindowById(465)
                                    dialogframe.Close()
                                    WizardEnd(None, 465, 'Chronos Monitor Configuration')            
                                except:
                                    WizardEnd(None, 465, 'Chronos Monitor Configuration')
                    subprocess.Popen(['osascript', '-e', '''\
                        tell application "System Events"
                          set procName to name of first process whose unix id is %s
                        end tell
                        tell application procName to activate
                    ''' % os.getpid()])
                    mes="run wizard first"

                                                           
    ##                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)
                    self.minuteSave(self)
                    #print ('tstart2')
                    if cocoastart==False:
                        #sc = self.SniffCocoa()
                        #sc.run()
                        cocoastart=True
                    #print ('tstart3')
                    try:
##                        if hmh==False:
##                            try:
##                                
##                                hm.MouseAllButtonsDown = OnMouseEvent
##                                #hm.MouseMove = asNoEvent
##                                # set the hook user["ID",to]
##                                hm.HookMouse()
##                                #pythoncom.PumpMessages
##                            finally:
##                                hmh=True
  
                        mes='-'+user["nom",to]+'-connected-'
                        #self.dc.message.SetEditable(True)
                        if invisible==False:
                            self.dc.message.SetValue(unicode(mes))
                        #elf.dc.message.SetEditable(False)
                        start=True
                        if ssyncro==True:self.chargeDossier()
                        timer.Start(milliseconds=60000, oneShot=False)

                        if syncrotip=='cont':
                            try:
                                conn_string = "host='"+str(users['serverip'])+"' dbname='chronos-monitor.com' user='chronos' password='gortex855'"
                                connec = psycopg2.connect(conn_string)
                                connec.set_client_encoding('UTF8')
                                cursex = connec.cursor()
                                conex=True
                                self.minuteView(resac,'full')
                                self.minuteView(resac,'condensed')
                                print ('good conex')
                            except:
                                mes="no internet, syncro off"
                                if invisible==False:
                                    self.dc.message.SetValue(unicode(mes))
                                conex=False
                                syncrotip='manu'
                                print (str(mes))
                        if str(on_open)=="True" or on_open==True:
                            #print '1245478'
                            try:
                                frame=wx.FindWindowById(444)
                                if frame.IsShown():
                                    frame.Hide()
                                    #print '12457810'
                                #else:
                                    #print '12457814'
                                #print '12457812'
                            except:
                                pass                                

                        #timerF.Start(milliseconds=10000, oneShot=False)
                    except:
                        
                        pass
            
                #pythoncom.PumpMessages()
            elif isconfig==False:
                mes="configurez d'abord le poste"
                if invisible==False:
                    self.dc.message.SetValue(unicode(mes))
        elif self.logoutRegion.Contains(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:
##                try:
##                    hm.UnhookMouse()
##                    #ctypes.windll.user32.PostQuitMessage(0)
##                    #del hm
##                    hmh=False
##                except:
##                    hmh=True
                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)
                if syncrotip=='cont' and conex==True:
                    self.minuteView(resac,'full')
                    self.minuteView(resac,'condensed')
                    cursex.close()
                    connec.close()
                timer.Stop()
                #timerF.Stop()
                #timerD.Stop()
                #sc.cancel()
                try:
                    observer.unschedule(stream)
                    observer.stop()
                except:
                    pass
                cocoastart=False
                mes='Disconnected'
##                for i in range(1,dossier['nombre']+1):
##                    watcher[i].kill()
                if invisible==False:
                    self.dc.message.SetValue(unicode(mes))
                    self.dc.display.SetValue("")
                start=False
            else:
                mes="Not connected"
                if invisible==False:
                    self.dc.message.SetValue(unicode(mes))
                
        elif self.optionsRegion.Contains(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'
            isconfig=os.path.isfile(TchemFSF)
            if start==True and isconfig==True:
                #try:
                conn_string = "host='"+str(users['serverip'])+"' dbname='chronos-monitor.com' user='chronos' password='gortex855'"
                conn = psycopg2.connect(conn_string)                        
                curs = conn.cursor()
                result=curs.execute("SELECT config,auto,export,password,sfiltre 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']=""
                    dusers['sfiltre']=""
                    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']+str(chain)
                        if p==4:dusers['sfiltre']=dusers['sfiltre']+str(chain)
                        p+=1
                    dusers['active']=True
                if dusers['config']=="0" and dusers['auto']=="0" and dusers['export']=="0":

                    line1="action not authorized"
                    line2="ask the authorization" 
                    line3="to your administrator"
                    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')
                subprocess.Popen(['osascript', '-e', '''\
                    tell application "System Events"
                      set procName to name of first process whose unix id is %s
                    end tell
                    tell application procName to activate
                ''' % os.getpid()])
                #mes="run wizard first"


##                except:
##                    line1="Please you have to connect"
##                    line2="to internet to configure" 
##                    line3="Work 'in' Memories."
##                    try:
##                        dialogframe = wx.FindWindowById(465)
##                        dialogframe.Close()
##                        WizardEnd(None, 465, 'Chronos Monitor Configuration')            
##                    except:
##                        WizardEnd(None, 465, 'Chronos Monitor Configuration')                        
            elif start==False and isconfig==True:

                line1="Please open"
                line2="your WIM's session" 
                line3="to achieve to the configuration."
                try:
                    dialogframe = wx.FindWindowById(465)
                    dialogframe.Close()
                    WizardEnd(None, 465, 'Chronos Monitor Configuration')            
                except:
                    WizardEnd(None, 465, 'Chronos Monitor Configuration')
                subprocess.Popen(['osascript', '-e', '''\
                    tell application "System Events"
                      set procName to name of first process whose unix id is %s
                    end tell
                    tell application procName to activate
                ''' % os.getpid()])
                #mes="run wizard first"


            elif start==False and isconfig==False:
                try:
                    optionsframe = wx.FindWindowById(458)
                    #optionsframe.Close()
                    if optionsframe.IsShown():
                        optionsframe.Show()
                    optionsframe.BringWindowToFront()
                   # mes="please run wizard"
                    if invisible==False:
                        self.dc.message.SetValue(unicode(mes))
                except:
                    Options(None, 458, 'Chronos Monitor Options')
                    #optionsframe.Show()
                    #app.BringWindowToFront()
                    #checkEvent = wx.CommandEvent(wx.wxEVT_ACTIVATE_APP,
                                     #WIM.GetId())
                    #WIM.ProcessEvent(checkEvent)
                    if invisible==False:
                        self.dc.message.SetValue(unicode(mes))
                subprocess.Popen(['osascript', '-e', '''\
                    tell application "System Events"
                      set procName to name of first process whose unix id is %s
                    end tell
                    tell application procName to activate
                ''' % os.getpid()])
                #mes="run wizard first"
 #               else:Options(None, 458, 'Chronos Monitor Options')
                    
##            except:
##                try:
##                    optionsframe = wx.FindWindowById(458)
##                    if optionsframe.IsShown():
##                        optionsframe.Show()
##                except:Options(None, 458, 'Chronos Monitor Options')
                
        elif self.listeRegion.Contains(pos):
            #self.dc.DrawBitmap(self.listef, 14, 40, True)
            wx.BufferedDC(wx.ClientDC(self),self.onliste)
            #self.dc.DrawBitmap(self.onliste, 10, 40, True)
            if start ==True:
                webbrowser.open(str(users['serverdomain'])+'/vipG.php?login='+str(user["login",to])+"&pid="+str(user["pass",to]))
            else:
                webbrowser.open('http://www.chronosmonitor.com/inscription.php?lang=en')
                mes="free subscribe to activate"
                if invisible==False:
                    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
        pos = event.GetPosition()
        if event.LeftIsDown()==False and self.bitmapRegion.Contains(pos):
            
            if self.syncRegion.Contains(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.Contains(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.Contains(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.Contains(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.Contains(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.Contains(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.Contains(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)
                    if invisible==False:
                        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 invisible==False:
            self.dc.message.Show()
            self.dc.message.SetValue(unicode(mes))
            self.dc.display.Show()
        if self.bitmapRegion.Contains(pos):
            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()
        return True

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]
#print '-begin-'
users={}
ElBrassoR()
USE_BUFFERED_DC = 1
users['serverip']='62.210.195.95'
users['serverdomain']='http://www.chronosmonitor.com'
HOST_IP='62.210.195.95'
HOST_DOMAIN='http://www.chronosmonitor.com'
reset=False
ssyncro=False
analyse=False
analysereset=False
question=False
start=False
deltatrsp=255
dinac=60
#print '-begin-2'
#print '-begin-31'
#print '-begin-32'
#path = os.getcwd()
#print '-begin-33'

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))

oscurdir1=get_main_dir()
i=len(oscurdir1)
oscurdir=""
torgol=False
#print (oscurdir1)
for x in range(0,i):
    try:
        if oscurdir1[x:int(x+8)]=='/WIM.app':
            torgol=True
            break
        else:
            oscurdir=oscurdir+oscurdir1[x:x+1]
        #print (oscurdir1[x:int(x+8)])
    except:
        oscurdir=oscurdir+oscurdir1[x:x+1]
if torgol==False:
    oscurdir=oscurdir1
    
#print (oscurdir)
    
#sprint '-begin-4'+str(oscurdir)os.path.realpath(sys.executable)
try:
    TchemMSF=oscurdir+os.sep+'wok'+os.sep+'conf'+os.sep+'hrd.gwh'
    invfile = open(TchemMSF, 'r')
    invfile.close()
    invisible=True
except:
    invisible=False
#print '-begin-5'
##app=wx.App(0)
##Widget(None, 444, 'Chronos Monitor')
##enter=False
###print '-begin-6'
###app.SetTopWindow(frameO)
##app.MainLoop()
class WIM(wx.App):
    global oscurdir,invisible
    def __init__(self, *args, **kwargs):
        wx.App.__init__(self, *args, **kwargs)
        
        # This catches events when the app is asked to activate by some other
        # process
        if invisible==False:
            self.Bind(wx.EVT_ACTIVATE_APP, self.OnActivate)


    def BringWindowToFront(self):
        try: # it's possible for this event to come when the frame is closed
            self.GetTopWindow().Raise()
        except:
            pass
        
    def OnActivate(self, event):
        # if this is an activate event, rather than something else, like iconize.
        if event.GetActive():
            self.BringWindowToFront()
        event.Skip()

    def OnInit(self):

        frame = Widget(None, 444, 'Chronos Monitor')
        if invisible==False:
            frame.Show()

##        import sys
##        for f in  sys.argv[1:]:
##            self.OpenFileMessage(f)
##
        return True
##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))
app = WIM(False)
enter=False
app.MainLoop()
