#!/usr/bin/env python

# -*- coding: utf8 -*- 

#***********************************************************************
# pysycache : a program for learn to use the mouse
# Copyright (C) 2005-2007 Vincent DEROO (vincent.pysycache@free.fr) 
# 
# This program is free software; you can redistribute it and/or 
# modify it under the terms of the GNU General Public License 
# as published by the Free Software Foundation; either version 2 
# of the License, or (at your option) any later version. 
# 
# This program is distributed in the hope that it will be useful, 
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details. 
# 
# You should have received a copy of the GNU General Public License 
# along with this program; if not, write to the Free Software 
# Foundation, Inc. : 
# 51 Franklin Street, Fifth Floor, Boston, MA02110-1301, USA
#***********************************************************************



import pygame
from pygame.locals import *
import os, string
import random
import glob
import locale

import const
import datas



#*******************************************************************************
#
#*******************************************************************************
class BtnOfMenu:
	def __init__(self, background, id, imagenamegd, imagenametp, left = 0, top = 0, largeur = 0, hauteur = 0, actif = True, survol = True, debutsurvol = 0, isrelatif = True, visible = 1):
		self.id = id
		self.background = background				#nom du fichier de fond
		self.SecondPicture = imagenamegd				#nom de l'image si survol
		self.NormalPicture = imagenametp				#nom de l'image normal
		self.left = left
		self.top = top
		self.largeur = largeur
		self.hauteur = hauteur
		self.actif = actif						#pour les gros boutons et activer l'evt click (si = 1)
		self.survol = survol						#0 : pas survol
										#1 : survol
		self.debutsurvol = debutsurvol					#heure du debut de survol
		self.isrelatif = isrelatif
		self.visible = visible					#0 : invisible,  1 : visible
#		rectbkg = pygame.Rect([0, 0, 64, 64])

	def ClearBackground(self, background):
		screen = pygame.display.get_surface()

		#on colle l'ancien arriere plan (pour "effacer")
#		imagetmp, recttmp = datas.Load_image("images", self.background)
		tr2 = pygame.Rect([self.left, self.top, self.largeur, self.hauteur] )
		const.Gbackground_image.blit(background, [self.left, self.top], tr2 )
		screen.blit(background, [self.left, self.top], tr2 )


	def LoadNormalPicture(self, background):
		screen = pygame.display.get_surface()

		#on colle l'ancien arriere plan (pour "effacer")
		self.ClearBackground(background)

		#on colle l'image correspondante (la petite)
		imagetmp, recttmp = datas.Load_image("images", self.NormalPicture, None, not self.isrelatif)
		(larg, haut) = imagetmp.get_size()

		if self.largeur * self.hauteur > 0:
			oldleft = self.left
			oldtop = self.top
			oldlargeur = self.largeur
			oldhauteur = self.hauteur
		else:
			oldleft =  self.left
			oldtop = self.top
			oldlargeur = larg
			oldhauteur = haut

		self.largeur = larg
		self.hauteur = haut
		self.left = oldleft + int( ( oldlargeur - self.largeur ) / 2) 
		self.top = oldtop + int( ( oldhauteur - self.hauteur ) / 2) 
		self.survol = 0
		self.debutsurvol = 0
		self.actif = False
		const.GIdBtnSurvol = 99
		const.Gbackground_image.blit(imagetmp, (self.left, self.top))
		screen.blit(imagetmp, (self.left, self.top))

	def LoadSecondPicture(self, background, filesound = 'btnmenu.wav', WithSound = True):
		if WithSound == True:
			datas.Load_sound("sounds", filesound)

		screen = pygame.display.get_surface()

		#on colle l'ancien arriere plan (pour "effacer")
		self.ClearBackground(background)

		oldleft = self.left
		oldtop = self.top
		oldlargeur = self.largeur
		oldhauteur = self.hauteur

		#on colle l'image correspondante (la plus grande)
		imagetmp, recttmp = datas.Load_image("images", self.SecondPicture, None, not self.isrelatif)
		(self.largeur, self.hauteur) = imagetmp.get_size()
		self.left = oldleft - int( ( - oldlargeur + self.largeur ) / 2)
		self.top = oldtop - int ( ( - oldhauteur + self.hauteur ) / 2) 
		const.Gbackground_image.blit(imagetmp, (self.left, self.top))
		screen.blit(imagetmp, (self.left, self.top))

	def ShowHelpOfMenu(self, imgdest):
		myfont = os.path.join(const.GRepPysycache, 'fonts', const.GFontName ).encode(const.GConsoleLocale)
		font = pygame.font.Font(myfont, 20)
		textcolor = 46, 113, 169
		screen = pygame.display.get_surface()

		myrep = os.path.join(const.GRepPysycache, 'lang', const.GMyLocale )

		#joue le fichier d'aide
		if const.GWithSound == 1:
			if const.GWithHelp == 1 :
				dirname = os.path.join(const.GRepPysycache, 'lang', const.GMyLocale)
				filename = 'menu' + str(self.id) + '.ogg'
				datas.Load_sound(dirname, filename)
		
		#affiche l'aide
		if os.path.isdir(myrep):
			filename = os.path.join(const.GRepPysycache, 'lang', const.GMyLocale , 'menu' + str(self.id) + '.txt')
		else :
			filename = os.path.join(const.GRepPysycache, 'lang', 'en_EN' , 'menu' + str(self.id) + '.txt')
			
		filename = os.path.join(const.GRepPysycache, 'lang', const.GMyLocale , 'menu' + str(self.id) + '.txt')
		if os.path.isfile(filename):
			f = open(filename, 'r')
			lignes  = f.readlines()
			cptligne = 0
			for j in lignes:
				j = j.strip()
#				text = font.render(unicode(j, "utf-8"), 1, textcolor)
				text = font.render(j.decode("utf-8", "ignore"), 1, textcolor)
				imgdest.blit(text, (195, 361 + 25 * cptligne))
				screen.blit(text, (195, 361 + 25 * cptligne))

				cptligne += 1
			f.close()

			pygame.display.update()



#*******************************************************************************
#
#*******************************************************************************
class MouseOfActivity(pygame.sprite.Sprite):
	"""This class is for the mouse"""
	def __init__(self, left, top, filename):
		pygame.sprite.Sprite.__init__(self) 				#call Sprite intializer
		dirname = os.path.join(const.GRepPysycache, "images")
		self.image, self.rect = datas.Load_image(dirname, filename)
		self.largeur = 64
		self.hauteur = 64
		self.rect.left = left 
		self.rect.top = top
		self.oldleft = left
		self.oldtop = top
		
		const.GMaSourisCurrentPositionX = left
		const.GMaSourisCurrentPositionY = top
		const.GMaSourisOldPositionX = left
		const.GMaSourisOldPositionY = top
		
		#on positionne la souris !
		pygame.event.clear()
		pygame.mouse.set_pos((left, top))

	def changepicture(self, newfilename):
		oldleft = self.rect.left
		oldtop = self.rect.top
		dirname = os.path.join(const.GRepPysycache, "images")
		self.image, self.rect = datas.Load_image(dirname, newfilename)
		screen = pygame.display.get_surface()
		self.rect.left = oldleft
		self.rect.top = oldtop
		screen.blit(self.image, (oldleft, oldtop))

	def move(self, imgbck, limX = -1, limY = -1, limXX = -1, limYY = -1):
		#------------- deplacement de la souris (avec le pointeur) -------------
		screen = pygame.display.get_surface()
#			OK mais lourd
#			screen.blit(Gbackground_image, (0,0))
		#on efface la position actuelle de la souris (avant son deplacement)
#		screen.blit(const.Gbackground_image, (self.oldleft, self.oldtop), (self.oldleft, self.oldtop, 64, 64))
		screen.blit(imgbck, (self.oldleft, self.oldtop), (self.oldleft, self.oldtop, 64, 64))

		#- verification des limites (pour que la souris soit toujours visible --
		if limX == -1 :
			datas.VerifLimitesSouris()
		else:
			datas.VerifLimitesSouris(limX, limY, limXX, limYY)
		
		#deplacement de la souris a sa nouvelle position
		self.rect.move_ip(const.GMaSourisCurrentPositionX - self.oldleft, const.GMaSourisCurrentPositionY - self.oldtop)

		#------------------ Sauvegarde des anciennes valeurs -------------------
		self.oldleft = const.GMaSourisCurrentPositionX
		self.oldtop = const.GMaSourisCurrentPositionY















#*******************************************************************************
#
#*******************************************************************************
class Score:
	Player = ""
	Duration = 99


#*******************************************************************************
#
#*******************************************************************************
class BestScores:
	def __init__(self, activityname):
		self.activity = activityname
		self.TabScoreNormaux = []
		self.TabScoreFantome = []
		self.ScoreMiniNormal = 99
		self.ScoreMiniFantom = 99

		#---------------- recherche du meilleur score normal -------------------
		fichier = os.path.join(const.GRepScores, activityname, 'normal.txt')
		cptligne = 0
		if os.path.isfile(fichier):
			#afficher le contenu du fichier
			f = open(fichier, 'r')
			lignes  = f.readlines()
			for lig in lignes:
				lig = lig.strip()
				lig = lig.split('|')

				if len(lig) < 2:
					continue

				sco = Score()
				sco.Player = lig[0].decode("utf-8", "ignore")
				sco.Duration = float(lig[1])
				self.ScoreMiniNormal = float(lig[1])
				self.TabScoreNormaux.append(sco)
				cptligne += 1

			f.close()
		if cptligne == 0:
			self.ScoreMiniNormal = 99
		elif cptligne < 8:
			self.ScoreMiniNormal = 99

		#---------------- recherche du meilleur score fantome -------------------
		fichier = os.path.join(const.GRepScores, activityname, 'fantom.txt')
		cptligne = 0
		if os.path.isfile(fichier):
			#afficher le contenu du fichier
			f = open(fichier, 'r')
			lignes  = f.readlines()
			for lig in lignes:
				lig = lig.strip()
				lig = lig.split('|')

				if len(lig) < 2:
					continue

				sco = Score()
				sco.Player = lig[0].decode("utf-8", "ignore")
				sco.Duration = float(lig[1])
				self.ScoreMiniFantom = float(lig[1])
				self.TabScoreFantome.append(sco)
				cptligne += 1

			f.close()
		if cptligne == 0:
			self.ScoreMiniFantom = 99
		elif cptligne < 8:
			self.ScoreMiniFantom = 99

	def Save(self):
		#activite normale
		filename = os.path.join(const.GRepScores, self.activity, 'normal.txt')
		i = 0
		file = open(filename,'w')
		for tabscore in self.TabScoreNormaux:
			if i == 8 :
				break
			str2 = tabscore.Player + "|" + str(tabscore.Duration) + "\n"
			file.write(str2.encode("utf-8", "ignore"))
			i += 1
		file.close()

		#activite fantome
		filename = os.path.join(const.GRepScores, self.activity, 'fantom.txt')
		i = 0
		file = open(filename,'w')
		for tabscore in self.TabScoreFantome:
			if i == 8 :
				break
			str2 = tabscore.Player + "|" + str(tabscore.Duration) + "\n"
			file.write(str2.encode("utf-8", "ignore"))
			i += 1
		file.close()

	def InsertNewScoreNormal(self, playername, newduration):
		sco = Score()
		sco.Player = playername
		sco.Duration = newduration

		found = 0
		i = 0
		for tabscore in self.TabScoreNormaux :
			if tabscore.Duration > newduration:
				#on a un plus grand que soit : on ajoute le nouveau
				self.TabScoreNormaux.insert(i, sco)
				found = 1
				break
			i += 1

		if found == 0:
			self.TabScoreNormaux.append(sco)

		#mise a jour du minimum
		self.ScoreMiniNormal = 0
		i = 0
		for tabscore in self.TabScoreNormaux:
			if i == 8 :
				break
			if tabscore.Duration > self.ScoreMiniNormal:
				self.ScoreMiniNormal = tabscore.Duration
			i += 1
		if i == 0:
			self.ScoreMiniNormal = 99
		elif i < 8:
			self.ScoreMiniNormal = 99
		datas.DebugMessage("")
		datas.DebugMessage("New score : %i" % self.ScoreMiniNormal)

	def InsertNewScoreFantom(self, playername, newduration):
		sco = Score()
		sco.Player = playername
		sco.Duration = newduration

		found = 0
		i = 0
		for tabscore in self.TabScoreFantome :
			if tabscore.Duration > newduration:
				#on a un plus grand que soit : on ajoute le nouveau
				self.TabScoreFantome.insert(i, sco)
				found = 1
				break
			i += 1

		if found == 0:
			self.TabScoreFantome.append(sco)

		#mise a jour du minimum
		self.ScoreMiniFantom = 0
		i = 0
		for tabscore in self.TabScoreFantome:
			if i == 8 :
				break
			if tabscore.Duration > self.ScoreMiniFantom:
				self.ScoreMiniFantom = tabscore.Duration
			i += 1
		if i == 0:
			self.ScoreMiniFantom = 99
		elif i < 8:
			self.ScoreMiniFantom = 99
		datas.DebugMessage("")
		datas.DebugMessage("New score : %i " % self.ScoreMiniFantom)


	def ShowScores(self, idlang, defaulttext):
		"""Show scores in a window """
		imgtmp, recttmp = datas.Load_image("images", "fond-scores.png")
		#titre
		datas.WriteTextInLang("SCOBEST3", "Default", imgtmp, -1, 10, 40)
		datas.WriteTextInLang(idlang, defaulttext, imgtmp, -1, 55, 40)

		myfont = os.path.join(const.GRepPysycache, 'fonts', const.GFontName).encode(const.GConsoleLocale)
		font = pygame.font.Font(myfont, 22)
		textcolor = 46, 113, 169

		#------------------ lire le fichier de scores normal -------------------
		fichier = os.path.join(const.GRepScores, self.activity, 'normal.txt')
		datas.DebugMessage("File of score : %s " % fichier)
		if os.path.isfile(fichier):
			#afficher le contenu du fichier
			f = open(fichier, 'r')
			lignes  = f.readlines()
			cptligne = 0
			for lig in lignes:
				if cptligne == 8:
					break
				lig = lig.strip()
				lig = lig.split('|')

				if len(lig) < 2:
					continue

				if len(lig[0]) > 32:
#					str = unicode(lig[0], "utf-8")
					str = lig[0].decode("utf-8", "ignore")
					text = font.render(str[0:31], 1, textcolor)
				else:
#					text = font.render(unicode(lig[0], "utf-8"), 1, textcolor)
					text = font.render(lig[0].decode("utf-8", "ignore"), 1, textcolor)
				imgtmp.blit(text, (270, 110 + 24 * cptligne)) 
#				text1 = font.render(unicode(lig[1], "utf-8"), 1, textcolor)
				text1 = font.render(lig[1].decode("utf-8", "ignore"), 1, textcolor)
				imgtmp.blit(text1, (600, 110 + 24 * cptligne)) 

				cptligne += 1
			f.close()


		#--------------- lire le fichier de score fantomes -----------------
		fichier = os.path.join(const.GRepScores, self.activity, 'fantom.txt')
		datas.DebugMessage("File of score : %s " % fichier)
		if os.path.isfile(fichier):
			#afficher le contenu du fichier
			f = open(fichier, 'r')
			lignes  = f.readlines()
			cptligne = 0
			for lig in lignes:
				if cptligne == 8:
					break
				lig = lig.strip()
				lig = lig.split('|')

				if len(lig) < 2:
					continue

				if len(lig[0]) > 32:
#					str = unicode(lig[0], "utf-8")
					str = lig[0].decode("utf-8", "ignore")
					text = font.render(str[0:31], 1, textcolor)
				else:
#					text = font.render(unicode(lig[0], "utf-8"), 1, textcolor)
					text = font.render(lig[0].decode("utf-8", "ignore"), 1, textcolor)
				imgtmp.blit(text, (270, 330 + 24 * cptligne)) 
#				text1 = font.render(unicode(lig[1], "utf-8"), 1, textcolor)
				text1 = font.render(lig[1].decode("utf-8", "ignore"), 1, textcolor)
				imgtmp.blit(text1, (600, 330 + 24 * cptligne)) 

				cptligne += 1
			f.close()

		#-------------------- affichage sur l'ecran ------------------------
		screen = pygame.display.get_surface()  
		const.Gbackground_image.blit(imgtmp, (0, 0))
		screen.blit(imgtmp, (0, 0))



import pysyscores




#*******************************************************************************
#                                   Classes                                    #
#*******************************************************************************


class ApplicationPysy:
	def __init__(self) :
		pass

	def InitializeApp(self, DirThemes, ActName):
		self.DirWithThemes = DirThemes					#the directory with the themes
		self.ActivityName = ActName						#nom raccourcis de l'activite
		self.Background, rectmp = datas.Load_image("images", "fond-" + self.ActivityName + ".png")
		self.BackgroundClear, rectmp = datas.Load_image("images", "fond-" + self.ActivityName + ".png")
		self.Scores = BestScores(self.DirWithThemes)	#les meilleurs scores
		self.TabBtn = []
		self.IdxThemes = 0								#numero du theme utilise
		self.IdxFileDfg = 0								#numero du fichier dfg utilise
		self.LstFicConfig = []							#liste des fichiers de config dans le theme
		self.LstThemesOfActivity = []   				#liste de tous les themes de l'activite jouee
														#est obtenue a partir d'une recherche dans le repertoire themes-xxxxx
		self.Level = 0
		self.ShowOnlyChrono = 0							#sur l'evt chrono : 0 on fait voir tout
														#					1 on fait voir que l'image du chrono
		self.TimeWaitAfterWin = 1000					#temps d'attente une fois que l'on a gagne
		self.WaitForClick = False


	#***************************************************************************
	# Recherche tous les themes d'une activite 
	# (a partir de tous les sous repertoires du repertoire du theme de l'activite)
	# et initialise GIdxThemes 
	#***************************************************************************
	def SearchAllThemesOfActivity(self):
		""" Change logo of a theme """
		#vider
		self.LstThemesOfActivity[:] = []

		#--------- on va chercher dans le repertoire de l'application --------------
		repertoire = os.path.join(const.GRepPysycache, self.DirWithThemes)
		datas.DebugMessage("")
		datas.DebugMessage("Search all themes of the activity in %s " % repertoire)
		for nom in os.listdir(repertoire):
			#ne prendre que les repertoires
			isrep = os.path.join(const.GRepPysycache, self.DirWithThemes, nom)
			if os.path.isdir(isrep):
				datas.DebugMessage("... found %s " % nom)
				self.LstThemesOfActivity.append(nom)

		#---------- on va chercher dans le repertoire de l'utilisateur -------------
		repertoire = os.path.join(const.GRepPersoUser, self.DirWithThemes)
		datas.DebugMessage("")
		datas.DebugMessage("Search all themes of the activity in %s " % repertoire)
		for nom in os.listdir(repertoire):
			#ne prendre que les repertoires
			isrep = os.path.join(const.GRepPersoUser, self.DirWithThemes, nom)
			if os.path.isdir(isrep):
				#est-ce que ce nom est deja pris ?
				ok = 0
				for obj in self.LstThemesOfActivity:
					if obj == nom :
						ok = 1
						break

				if ok == 0 :
					datas.DebugMessage("... found %s " % nom)
					self.LstThemesOfActivity.append(nom)

		#------------------ choix au hasard d'un de ces themes ---------------------
		if len(self.LstThemesOfActivity) == 1:
			self.IdxThemes = 0
		else:
			self.IdxThemes = random.randint(0, len(self.LstThemesOfActivity) - 1)

		datas.DebugMessage("")
		datas.DebugMessage("theme name used : %s " % self.LstThemesOfActivity[self.IdxThemes] )


	#***************************************************************************
	#
	#***************************************************************************
	def GetLevelForDfgFile(self, levelname):
		#a surcharger par chaque application

		return levelname


	#***************************************************************************
	# Find all configuration files for a theme of an activity                      #
	# We search all *.dfg files                                                    #
	# and choice randomly one file (and initilize GIdxFileDfg)                     #
	#***************************************************************************
	def SearchAllConfigFiles(self):
		""" Find all configuration files (*.dfg) of a theme directory """
		level = ""

		level = self.GetLevelForDfgFile(level)

		themename = self.LstThemesOfActivity[self.IdxThemes]

		#chercher dans le repertoire de l'application
		if level == "" :
			filtre = os.path.join(const.GRepPysycache, self.DirWithThemes, themename, '*.dfg')
		else :
			filtre = os.path.join(const.GRepPysycache, self.DirWithThemes, themename, level, '*.dfg')

		datas.DebugMessage("")
		datas.DebugMessage("search all dfg file for the theme %s " % themename)

		#vider
		self.LstFicConfig[:] = []

		datas.DebugMessage("")
		datas.DebugMessage("   Pysycache directory")
		#remplir 
		for nom in glob.glob(filtre):
			if os.path.isfile(nom):
				#--- recuperation du nom (avec chemin) du fichier de definition ----
				datas.DebugMessage("... found %s " % nom)

				if level == "":
					nomdfg = os.path.join(const.GRepPysycache, self.DirWithThemes, themename, nom)
				else :
					nomdfg = os.path.join(const.GRepPysycache, self.DirWithThemes, themename, level, nom)

				self.LstFicConfig.append(nomdfg)

		#chercher dans le repertoire de l'utilisateur
		datas.DebugMessage("")
		datas.DebugMessage("   User directory")

		if level == "":
			filtre = os.path.join(const.GRepPersoUser, self.DirWithThemes, themename, '*.dfg')
		else :
			filtre = os.path.join(const.GRepPersoUser, self.DirWithThemes, themename, level, '*.dfg')

		for nom in glob.glob(filtre):
			if os.path.isfile(nom):
				#--- recuperation du nom (hors chemin) du fichier de definition ----
				datas.DebugMessage("... found %s " % nom)

				if level == "":
					nomdfg = os.path.join(const.GRepPysycache, self.DirWithThemes, themename, nom)
				else :
					nomdfg = os.path.join(const.GRepPysycache, self.DirWithThemes, themename, level, nom)
				self.LstFicConfig.append(nomdfg)

		#choisir un fichier de configuration au hasard
		if len(self.LstFicConfig) == 1:
			self.IdxFileDfg = 0
		else :
			self.IdxFileDfg = random.randint(0, len(self.LstFicConfig) - 1)

		datas.DebugMessage("")
		datas.DebugMessage("dfg file used : %s " % self.LstFicConfig[self.IdxFileDfg] )


	#***************************************************************************
	# change le logo du theme (a partir du fichier logo.png du theme)
	#***************************************************************************
	def ChangeLogoOfActivity(self):
		""" Change logo of a theme """
		nom = self.LstFicConfig[self.IdxFileDfg]

		#--- recuperation du nom (hors chemin) du fichier de definition ----
		(path, name) = os.path.split(nom)
		filename = os.path.join(path, "logo.png")


		if os.path.isfile(filename) == True:
			imgtmp, recttmp = datas.Load_image("", filename, None, True)
		else:
			imgtmp, recttmp = datas.Load_image("images", "logo.png")
			filename = os.path.join(const.GRepPysycache, "images", "logo.png")

		#mise a jour de l'image du theme
		for btn in self.TabBtn:
			if btn.id == 5:
				#the id of the logo button
				self.Background.blit(imgtmp, (btn.left, btn.top), (0, 0, btn.largeur, btn.hauteur))
				btn.SecondPicture = filename
				btn.NormalPicture = filename


	#***************************************************************************
	#
	#***************************************************************************
	def ManageSurvol(self, event0, event1):
		"""Verify if a button is pass over... and prepare it's big size """
		ok = 0
		for btn in self.TabBtn :
			if btn.visible == 0 :
				continue
			if ( event0 + const.DEMISOURIS >= btn.left ) & ( event0 + const.DEMISOURIS <= btn.left + btn.largeur ) & ( event1 + const.DEMISOURIS >= btn.top  ) & ( event1 + const.DEMISOURIS <= btn.top + btn.hauteur ) :
				if btn.survol == 0:
					#le survol n'existait pas encore pour ce bouton
					if btn.id != const.GIdBtnSurvol:
						#c'etait un autre bouton qui etait survole
						for btn2 in self.TabBtn :
							if btn2.id == const.GIdBtnSurvol:
								screen = pygame.display.get_surface()
								btn2.LoadNormalPicture(self.Background, self.BackgroundClear)
	#							screen.blit(const.Gbackground_image,(btn2.left - 20, btn2.top - 20) ,(btn2.left - 20, btn2.top - 20, 130, 130) )
	#?							pygame.display.update((btn2.left - 20, btn2.top - 20, btn2.largeur + 40, btn2.hauteur + 40))
								break
					#on passe le bouton actuel en attente de survol
					ok = 1
					const.GIdBtnSurvol = btn.id
					btn.survol = 1
					btn.debutsurvol = pygame.time.get_ticks()
					pygame.time.set_timer (const.EVTSURVOL, 500 )
				else:
					ok = 1
				break

		if ok == 0:
			if const.GIdBtnSurvol != 99:
				#on sort d'un survol de bouton et on est sur aucun autre bouton
				pygame.time.set_timer (const.EVTSURVOL, 0 )
				screen = pygame.display.get_surface()
				for btn2 in self.TabBtn :
					if btn2.id == const.GIdBtnSurvol:
						btn2.LoadNormalPicture(self.Background, self.BackgroundClear)
	#					screen.blit(const.Gbackground_image,(btn2.left - 20, btn2.top - 20) ,(btn2.left - 20, btn2.top - 20, 130, 130) )
	#?					pygame.display.update((btn2.left - 20, btn2.top - 20, btn2.largeur + 40, btn2.hauteur + 40))
						break
				const.GIdBtnSurvol = 99
				const.GLstSouris.draw(screen)
				pygame.display.update()


	#***************************************************************************
	#
	#***************************************************************************
	def DoImageNext(self) :
		hasard = 1
		#image apres (dans le theme)
		if self.IdxFileDfg < len(self.LstFicConfig) - 1:
			self.IdxFileDfg = self.IdxFileDfg + 1
		else:
			self.IdxFileDfg = 0

		#transition
		datas.ShowTransitionOfTheme(const.GDureeTransition, "fond-" + self.ActivityName + ".png")

		#lire ce fichier de configuration
		self.ReadDfgFile()

		#mise en place de l'interface du jeu
		self.InitGame(True)


	#***************************************************************************
	#
	#***************************************************************************
	def DoImagePrev(self) :
		hasard = 1
		if self.IdxFileDfg > 0:
			self.IdxFileDfg = self.IdxFileDfg - 1
		else:
			self.IdxFileDfg = len(self.LstFicConfig) - 1

		#transition
		datas.ShowTransitionOfTheme(const.GDureeTransition, 'fond-' + self.ActivityName + '.png')

		#lire ce fichier de configuration
		self.ReadDfgFile()

		#mise en place de l'interface du jeu
		self.InitGame(True)

		self.ShowBtnMenus()

		screen = pygame.display.get_surface()
		const.GLstSouris.draw(screen)
		pygame.display.update()


	#***************************************************************************
	# Initialisations propres a l'activite
	#***************************************************************************
	def InitActivity(self, WithHasard):
		#a surcharger par chaque application
		self.Background, rectmp = datas.Load_image("images", "fond-" + self.ActivityName + ".png")
		self.BackgroundClear, rectmp = datas.Load_image("images", "fond-" + self.ActivityName + ".png")


	#***************************************************************************
	# affiche les boutons sur l'image d'arriere plan
	#***************************************************************************
	def ShowBtnMenus(self):
		for btn in self.TabBtn:
			if (btn.visible == 1) : 
				btn.LoadNormalPicture(self.Background, self.BackgroundClear)
			else:
				btn.ClearBackground(self.Background, self.BackgroundClear)


	#***************************************************************************
	# renvoie le nom du fichie utilise pour la souris
	#***************************************************************************
	def SetMousePicture(self):
		return 'souris-' + self.ActivityName + '.png'


	#***************************************************************************
	#
	#***************************************************************************
	def InitGame(self, WithHasard):
		pygame.time.set_timer ( const.EVTFANTOME, 0 )

		screen = pygame.display.get_surface()
		pygame.event.clear()

		#partie a surcharger par chaque application
		self.InitActivity(WithHasard)

		#on reprend l'affichage commun a toutes les activites
		const.GLstSouris.empty()

		self.HideAndShowBtn()
		self.ShowBtnMenus()

		pygame.event.clear()
		const.GTypeSouris = const.EVENT_JEU0

		#dessin des secondes du chrono
		self.LoadSecondes()

		screen.blit(self.Background, (0, 0))

		const.GLstSouris.add(MouseOfActivity(const.GPosDepX, const.GPosDepY, self.SetMousePicture()) )
		for o in const.GLstSouris.sprites():
			o.move(self.Background)

		#redessin de la souris a sa position 
		const.GLstSouris.draw(screen)

		pygame.display.update()

		if const.GChrono == 1 :
			#on prend le temps 
			const.GTpsDebut = pygame.time.get_ticks()

		if const.GModeJeu == const.MODEFANTOM :
			pygame.time.set_timer ( const.EVTFANTOME, 1000 )



	#***************************************************************************
	#
	#***************************************************************************
	def HideAndShowBtn(self):
		"""Met a jour les boutons selon le niveau de detail de l'interface """
		screen = pygame.display.get_surface()

		#on verifie les limites du type d'affichage
		if const.GInterface > 2:
			const.GInterface = 0

		datas.DebugMessage("")
		datas.DebugMessage("Current display mode : %i" % const.GInterface)

		for btn in self.TabBtn :
			btn.survol = 0
			btn.debutsurvol = 0
			btn.actif = False

			if btn.id == 1:										#mode normal/fantome
				if const.GInterface >= 2:
					if const.GModeJeu == const.MODEFANTOM:
						btn.SecondPicture = 'move-mode1-gd.png'
						btn.NormalPicture = 'move-mode1.png'
					else:
						btn.SecondPicture =  'move-mode0-gd.png'
						btn.NormalPicture =  'move-mode0.png' 
					btn.visible = True
				else:
					btn.visible = False
			elif btn.id == 6:									#indicateur de niveau
				btn.SecondPicture = 'level' + str(const.GLevel) + '-gd.png'
				btn.NormalPicture = 'level' + str(const.GLevel) + '.png'
				if const.GInterface >= 2:
					btn.visible = True
				else:
					btn.visible = False
			elif btn.id == 7:									#chronometre
				if const.GInterface >= 2:
					if const.GLevel == 2:
						btn.visible = True
					else:
						btn.visible = False
				else:
					btn.visible = False
			elif btn.id == 3:									#image avant
				if const.GInterface >= 1:
					btn.visible = True
				else:
					btn.visible = False
			elif btn.id == 4:									#image apres
				if const.GInterface >= 1:
					btn.visible = True
				else:
					btn.visible = False
			else :
				btn.visible = True

		datas.DebugMessage("New display mode : %i" % const.GInterface)

		#on met a jour l'affichage
	#	ShowBtnMenus(const.Gbackground_image, TabBtn)
	#	pygame.display.update()



	#***************************************************************************
	#
	#***************************************************************************
	def ShowPerdu(self, okdessin):
		if ( float(pygame.time.get_ticks() - const.GTpsDebut)/1000 > 60) & (const.GChrono == 1):
			#le chronometre a termine plus vite que le joueur !
			#le chronometre existait : on supprime l'evenement
			pygame.time.set_timer (const.EVTCHRONO, 0 )
			screen = pygame.display.get_surface()

#			self.Background.blit(const.GChronoBas, (735, 10))
#			screen.blit(const.GChronoBas, (735, 10))
			imgperdu, imgfin_rect = datas.Load_image("images", "perdu.png")
			(perdularg, perduhaut) = imgperdu.get_size()
			screen.blit(imgperdu, ( (800 - perdularg) / 2, (600 - perduhaut) / 2))
			pygame.display.update()

			#attende de 3 secondes
			pygame.time.wait(3000)

			okdessin = 1

		return okdessin



	#***************************************************************************
	#
	#***************************************************************************
	def LoadSecondes(self):
		"""Charge les images des secondes """
		screen = pygame.display.get_surface()

		if const.GChrono == 1 :
#			const.GChronoCpt = const.GChronoLimit
#			self.Background.blit(const.GChronoHaut, (735, 10))
#			screen.blit(const.GChronoHaut, (735, 10))
#			pygame.display.update((735, 10, 64, 204))
#			const.GLstSouris.draw(screen)

			#on prend le temps 
			const.GTpsDebut = pygame.time.get_ticks()

			pygame.time.set_timer (const.EVTCHRONO, 1000 )  #toutes les secondes
		else:
			for btn in self.TabBtn :
				if btn.id == 7:
					self.StopChrono(btn)
					break

	#		pygame.time.set_timer (const.EVTCHRONO, 0 )  #arreter le chronometre
	#		const.Gbackground_image.blit(const.GChronoAP, (735, 60))
	#		screen.blit(const.GChronoAP, (735, 60))
	#		pygame.display.update((735, 60, 64, 135))
	#		const.GLstSouris.draw(screen)


	#***************************************************************************
	# Retour 0 : on a pas gagne
	#        1 : on a gagne  
	#***************************************************************************
	def OnAGagne(self, gagne):
		#a surcharger par chaque application

		return gagne




	#***************************************************************************
	# Show the file with the themes authors                                    #
	#***************************************************************************
	def ReadCreditOfDirectory(self, directory):
		myfont = os.path.join(const.GRepPysycache, 'fonts', const.GFontName).encode(const.GConsoleLocale)
		font = pygame.font.Font(myfont, 20)
		textcolor = 46, 113, 169

		screen = pygame.display.get_surface()
		img, rec = datas.Load_image("images", "fond5.png")

		#affichage des auteurs du theme
		repertoire = os.path.join(directory, self.DirWithThemes)

		if os.path.isdir(repertoire):
			for nom in os.listdir(repertoire):
				#ne prendre que les repertoires
				isrep = os.path.join(repertoire, nom)
				if os.path.isdir(isrep):
					fichier = os.path.join(repertoire, nom, 'credits.txt')
					datas.DebugMessage("")
					datas.DebugMessage("Credit of file : " + fichier)
					if os.path.isfile(fichier):
						screen.blit(img, (0,0))

						#copie du logo
						logoname = os.path.join(repertoire, nom, "logo.png")

						imglogo, imgrect = datas.Load_image("", logoname, None, True)
						screen.blit(imglogo, (734, 520))

						#afficher le contenu du fichier
						f = open(fichier, 'r')
						lignes  = f.readlines()
						cptligne = 0
						for j in lignes:
							j = j.strip()
#							text = font.render(unicode(j, "utf-8"), 1, textcolor)
							text = font.render(j.decode("utf-8", "ignore"), 1, textcolor)
							screen.blit(text, (50, 60 + 20 * cptligne)) 
							cptligne += 1
						f.close()
						pygame.display.update()

					#attente entre deux credits
					pygame.time.wait(1000 * const.GDureeTransition) 


	#***************************************************************************
	#
	#***************************************************************************
	def DoPlayerGagne(self):
		#a surcharger par chaque application
		pass


	#***************************************************************************
	#
	#***************************************************************************
	def Execute(self):
		datas.DebugMessage("")
		datas.DebugMessage("******************* %s  activity *******************" % self.ActivityName)

		screen = pygame.display.get_surface()

		#------------------ transition vers le jeu ------------------------
		datas.ShowTransitionOfTheme(const.GDureeTransition, 'fond-' + self.ActivityName + '.png')

		#---------------------- initialisations diverses -----------------------
		const.GIdBtnSurvol = 99
		const.GIdxThemes = 0
		self.IdxFileDfg = 0
		const.GModeJeu = const.MODENORMAL
		const.GTypeSouris = const.EVENT_NOVENT
		const.GLevel = const.GPrefUserInit.Level
		const.GInterface = const.GLevel
		const.GChrono = 0

		#activite click et dblclick
		const.GIdxImage = 0
		const.GItemToFound = 99

		const.GChronoAP.blit(self.Background, (0, 0), (735, 10, 64, 204)) 

		#------------------------ ajout des boutons ---------------------------
		self.TabBtn[:]=[]
		#mode du jeu - 0/1/2
		self.TabBtn.append(BtnOfApplication("", 1, 'move-mode1-gd.png', 'move-mode1.png', 750, 270))
		#indicateur de niveaux 
		self.TabBtn.append(BtnOfApplication("", 6, 'level' + str(const.GLevel) + '-gd.png', 'level' + str(const.GLevel) + '.png', 750, 320) )
		#mode chronometre
#		if const.GLevel == 2 :
		self.TabBtn.append(BtnOfApplication("", 7, 'btn-timer-off-gd.png', 'btn-timer-off.png', 750, 220) )
		#avant et apres
		self.TabBtn.append(BtnOfApplication("", 3, 'btn-prev-gd.png', 'btn-prev.png', 750, 370) )
		self.TabBtn.append(BtnOfApplication("", 4, 'btn-next-gd.png', 'btn-next.png', 750, 420) )
		#logo du theme
		self.TabBtn.append(BtnOfApplication("", 5, "logo.png", "logo.png", 735, 475) )
		#quitter
		self.TabBtn.append(BtnOfApplication("", 2, 'btn-quitter-gd.png', 'btn-quitter.png', 690, 545) )

		#-------------------- liste des boutons ----------------------
		self.HideAndShowBtn()

		#------------------- changer la souris en la forme appropriee -------------------------
		const.GLstSouris.empty()
		const.GLstSouris.add(MouseOfActivity(const.GPosDepX, const.GPosDepY, self.SetMousePicture()) )

		#initialisation propre au niveau
		self.DoInitLevel()

		#---------------- rechercher les themes disponibles ----------------------
		self.SearchAllThemesOfActivity()

		#---------- rechercher les fichiers de config d'un theme -------------------
		self.SearchAllConfigFiles()

		#changer le logo de l'activite
		self.ChangeLogoOfActivity()

		#lire ce fichier de configuration
		self.ReadDfgFile()

		#mise en place de l'interface du jeu
		self.InitGame(True)

		self.ShowBtnMenus()

		#-------------- entree dans la boucle principale --------------
		running = 1
		okdessin = 0
		gagne = 0
		while running:
			datas.Temporisation()
#			const.GTypeSouris = const.EVENT_JEU0

			#recherche des evt
			running = self.DetectEvent()
			
			#verification que l'on a gagne
			gagne = self.OnAGagne(gagne)
			if (gagne == 1) :
				#------------------------- on a tout decouvert -----------------
				pygame.event.clear()
				if const.GChrono == 1:
					#le chronometre existait : on supprime l'evenement
					pygame.time.set_timer (const.EVTCHRONO, 0 )
					#on prend le temps utilise pour tout decouvrir
					tpsutilise = float(pygame.time.get_ticks() - const.GTpsDebut)/1000
					datas.DebugMessage("******************* Used time : %f " % tpsutilise)
				const.GTypeSouris = const.EVENT_GAGNE

				#-- on affiche l'image definitive et on attend pour la faire voir --
				screen = pygame.display.get_surface()
				screen.blit(self.Background, (0,0))

	#			if const.GChrono == 1:
	#				const.GLstChrono.draw(screen)
				pygame.display.update()

				self.DoPlayerGagne()

				#attende de 2 secondes (pour faire voir l'image)
				pygame.time.wait(self.TimeWaitAfterWin)
	
				#----------------- on affiche l'image de gagne ---------------------
				datas.PlayWinnerSound()
	
				imggagne, imgfin_rect = datas.Load_image("images", "gagne.png")
				(larg, haut) = imggagne.get_size()
				screen.blit(imggagne, (const.MARGELEFT + (720 - larg) / 2, const.MARGETOP + (540 - haut) / 2))
				pygame.display.update()
	
				#attende de 3 secondes
				pygame.time.wait(3000)
	
				if const.GChrono == 1:
					#le chronometre existait : on le supprime
					#est-ce les meilleurs scores ?
					okscore = 0
					if const.GModeJeu == const.MODENORMAL:
						if tpsutilise < self.Scores.ScoreMiniNormal :
							okscore = 1
	
					if const.GModeJeu == const.MODEFANTOM :
						if tpsutilise < self.Scores.ScoreMiniFantom :
							okscore = 1
	
					if okscore == 1:
	#				const.GChrono = 0
						pysyscores.ShowWindow(1, self.ActivityName, tpsutilise, self.Scores)
				okdessin = 1
			else:
				okdessin = self.ShowPerdu(okdessin)

			if okdessin == 1:
				#on recharge une nouvelle image
				if len(self.LstFicConfig) > 1:
					if len(self.LstFicConfig) > 1:
						nvidx = random.randint(0, len(self.LstFicConfig) - 1)
					else:
						nvidx = 0
					if nvidx == self.IdxFileDfg:
						#si la meme image qu'actuellement, on fait un second essai
						if len(self.LstFicConfig) > 1:
							nvidx = random.randint(0, len(self.LstFicConfig) - 1)
						else:
							nvidx = self.IdxFileDfg = 0
					self.IdxFileDfg = nvidx

				#transition
				datas.ShowTransitionOfTheme(const.GDureeTransition, 'fond-' + self.ActivityName + '.png')

				#lire ce fichier de configuration
				self.ReadDfgFile()

				#mise en place de l'interface du jeu
				self.InitGame(True)

				const.GTypeSouris = const.EVENT_JEU0

				pygame.event.clear()

				okdessin = 0

		if const.GChrono == 1:
			#le chronometre existe : on le supprime
			for btn in self.TabBtn :
				if btn.id == 7:
					self.StopChrono(btn)
					break

		pygame.time.set_timer ( const.EVTFANTOME, 0 )
		self.EndOfActivity()


	#***************************************************************************
	# Initialisation propre a l'activite
	#***************************************************************************
	def DoInitLevel(self):
		#a surcharger par chaque application
		pass

	#***************************************************************************
	#
	#***************************************************************************
	def EndOfActivity(self):
		#a surcharger par chaque application
		pass

	#***************************************************************************
	#
	#***************************************************************************
	def DoTheMoveEvent(self):
		#a surcharger par chaque application
		pass


	#***************************************************************************
	#
	#***************************************************************************
	def DoTheVisibleEvent(self):
		#a surcharger par chaque application
		pass


	#***************************************************************************
	#
	#***************************************************************************
	def DoTheChronoEvent(self):
		"""Count down the seconds, and update the buttons of seconds """
		y = int(60 - float(pygame.time.get_ticks() - const.GTpsDebut)/1000)

		screen = pygame.display.get_surface()

		if y == 5:
			imgchrono, rectchrono = datas.Load_image("images", "chrono4.png")
			self.Background.blit(imgchrono, (736, 10))
			screen.blit(imgchrono, (736, 10))
		elif y == 15:
			imgchrono, rectchrono = datas.Load_image("images", "chrono3.png")
			self.Background.blit(imgchrono, (736, 10))
			screen.blit(imgchrono, (736, 10))
		elif y == 30:
			imgchrono, rectchrono = datas.Load_image("images", "chrono2.png")
			self.Background.blit(imgchrono, (736, 10))
			screen.blit(imgchrono, (736, 10))
		elif y >= 58:
			imgchrono, rectchrono = datas.Load_image("images", "chrono1.png")
			self.Background.blit(imgchrono, (736, 10))
			screen.blit(imgchrono, (736, 10))

		#effacer la zone
		tr2 = pygame.Rect([736, 80, 64, 100] )
		self.Background.blit(self.BackgroundClear, [736, 80], tr2 )
		screen.blit(self.BackgroundClear, [736, 80], tr2 )


		myfont = os.path.join(const.GRepPysycache, 'fonts', const.GFontName).encode(const.GConsoleLocale)
		font = pygame.font.Font(myfont, 40)
		textcolor =  128, 186, 234
		#titre
		text = font.render(str(y), 1, textcolor)
		
		#.convert_alpha()
		(larg, haut) = text.get_size()
		self.Background.blit(text, (736 + int((64 - larg) / 2), 80 ))
		screen.blit(text, (736 + int((64 - larg) / 2), 80 ))

		if self.ShowOnlyChrono == 0:
			const.GLstSouris.draw(screen)

		pygame.display.update()


	#***************************************************************************
	#
	#***************************************************************************
	def DoTheSurvolEvent(self):
		for btn in self.TabBtn :
			if btn.survol == 1:
				if pygame.time.get_ticks() - btn.debutsurvol > 1500:
					pygame.time.set_timer (const.EVTSURVOL, 0 )
					pygame.event.clear()
					btn.actif = True
	#				screen.blit(const.Gbackground_image,(obj.left - 20, obj.top - 20) ,(obj.left - 20, obj.top - 20, 130, 130) )
					btn.LoadSecondPicture(self.Background, self.BackgroundClear)
					#on met l'image au dessus de la souris
					imgtmp, rectmp = datas.Load_image("images", btn.SecondPicture, None, not btn.isrelatif)
					screen = pygame.display.get_surface()
					const.GLstSouris.draw(screen)
					screen.blit(imgtmp, (btn.left, btn.top) )
					pygame.display.update()

				break


	#***************************************************************************
	#
	#***************************************************************************
	def MotionBeforeMouse(self, event0, event1, str):
		#a surcharger par chaque application
		pass

	#***************************************************************************
	#
	#***************************************************************************
	def MotionAfterMouse(self, event0, event1, str):
		#a surcharger par chaque application
		pass

	#***************************************************************************
	#
	#***************************************************************************
	def UpdateChrono(self, btn):
		datas.DebugMessage("")
		datas.DebugMessage("Current chronometer mode : %i " % const.GChrono)

		if const.GChrono == 0:
			#le mode chronometre est arrete : on l'active
			imgtmp, rectmp = datas.Load_image("images", "btn-timer-on.png")
			filename = os.path.join(const.GRepPysycache, "images", "btn-timer-on.png")
			btn.NormalPicture = filename
			filename = os.path.join(const.GRepPysycache, "images", "btn-timer-on-gd.png")
			btn.SecondPicture = filename
			btn.image = imgtmp
			const.GChrono = 1
		else:
			#le chronometre existe : on le supprime
			self.StopChrono(btn)

		datas.DebugMessage("New chronometer mode : %i " % const.GChrono)


	#***************************************************************************
	#
	#***************************************************************************
	def DoOnMouseDown(self, event0, event1, str):
		#a surcharger par chaque application
		pass


	#***************************************************************************
	#
	#***************************************************************************
	def DoOnMouseUpAfterButtons(self, event0, event1):
		#a surcharger par chaque application
		pass


	#***************************************************************************
	#
	#***************************************************************************
	def DoOnMouseUpBeforeButtons(self, event0, event1):
		#a surcharger par chaque application
		pass


	#***************************************************************************
	#
	#***************************************************************************
	def DoTheFantomEvent(self):
		#a surcharger par chaque application
		pass

	#***************************************************************************
	#
	#***************************************************************************
	def StopChrono(self, btn):
		if const.GChrono == 1:
			datas.DebugMessage("")
			datas.DebugMessage("We stop the chronometer")

			const.GChrono = 0

			pygame.time.set_timer (const.EVTCHRONO, 0 )  #arreter le chronometre

			imgtmp, rectmp = datas.Load_image("images", 'btn-timer-off.png')
			filename = os.path.join(const.GRepPysycache, "images", 'btn-timer-off.png')
			btn.NormalPicture = filename
			filename = os.path.join(const.GRepPysycache, "images", 'btn-timer-off-gd.png')
			btn.SecondPicture = filename
			btn.image = imgtmp

			#effacer la zone
			screen = pygame.display.get_surface()
			tr2 = pygame.Rect([736, 10, 64, 180] )
			self.Background.blit(self.BackgroundClear, [736, 10], tr2 )
			screen.blit(self.BackgroundClear, [736, 10], tr2 )



	#***************************************************************************
	#
	#***************************************************************************
	def DoTheChangeLevel(self):
		self.ChangeLevel()



	#***************************************************************************
	#
	#***************************************************************************
	def DoTheChangeTheme(self):
		self.IdxThemes += 1
		if self.IdxThemes == len(self.LstThemesOfActivity):
			self.IdxThemes = 0

		#transition
		datas.ShowTransitionOfTheme(const.GDureeTransition, 'fond-' + self.ActivityName + '.png')

		#---------- rechercher les fichiers de config d'un theme -------------------
		self.SearchAllConfigFiles()

		#changer le logo de l'activite
		self.ChangeLogoOfActivity()

		#lire ce fichier de configuration
		self.ReadDfgFile()

		#mise en place de l'interface du jeu
		self.InitGame(True)

		self.ShowBtnMenus()


	#***************************************************************************
	#
	#***************************************************************************
	def DoTheChangeMode(self):
		#change le type du jeu (normal/fantome)
		const.GModeJeu += 1
		if const.GModeJeu >= const.MODEFANTOM + 1:
			const.GModeJeu = const.MODENORMAL

		if const.GModeJeu == const.MODENORMAL :
			datas.DebugMessage("Mode normal")
		else:
			datas.DebugMessage("Mode ghost")

		#transition
		datas.ShowTransitionOfTheme(const.GDureeTransition, 'fond-' + self.ActivityName + '.png')

		#lire ce fichier de configuration
		self.ReadDfgFile()

		#mise en place de l'interface du jeu
		self.InitGame(False)

		self.ShowBtnMenus()


	#***************************************************************************
	#
	#***************************************************************************
	def DoTheChronometer(self, btn):
		if const.GLevel == 2:
			self.UpdateChrono(btn)
			#transition
			datas.ShowTransitionOfTheme(const.GDureeTransition, 'fond-' + self.ActivityName + '.png')
			
			#lire ce fichier de configuration
			self.ReadDfgFile()

			#mise en place de l'interface du jeu
			self.InitGame(False)


	#***************************************************************************
	#
	#***************************************************************************
	def DetectEvent(self):
		#cas qui font eviter la gestion des evenements
		if const.GTypeSouris == const.EVENT_GAGNE:
			return 1
		if const.GTypeSouris == const.EVENT_NOVENT:
			return 1
		if const.GTypeSouris == const.EVENT_JEU2:
			return 1

		#traitement des evenements
		for event in pygame.event.get():
			if event.type == QUIT:
				return 0
			elif event.type == const.EVTCHRONO:
				self.DoTheChronoEvent()
#				return 1
			elif event.type == const.EVTSURVOL:
				self.DoTheSurvolEvent()
#				return 1
			elif event.type == const.EVTFANTOME:
				self.DoTheFantomEvent()
				return 1
			elif event.type == const.EVTMOVE:
				self.DoTheMoveEvent()
#				return 1
			elif event.type == const.EVTVISIBLE:
				self.DoTheVisibleEvent()
				return 1
			elif event.type == KEYUP:
				if event.key == K_ESCAPE:
					return 0
				elif event.key == K_RIGHT:
					self.DoImageNext()
					return 1
				elif event.key == K_LEFT:
					self.DoImagePrev()
					return 1
				elif event.key == K_UP:
					#change le niveau
					self.DoTheChangeLevel()
					return 1
				elif event.key == K_F2:
					#change la visibilite des boutons
					screen = pygame.display.get_surface()
					const.GInterface += 1
					self.HideAndShowBtn()
					self.ShowBtnMenus()
					const.GLstSouris.draw(screen)
					pygame.display.update()
					return 1
				elif event.key == K_F3:
					#change le theme
					self.DoTheChangeTheme()
					return 1
				elif event.key == K_F4:
					#change le mode
					self.DoTheChangeMode()
					return 1
				elif event.key == K_F5:
					#lance/stoppe le chronometre
					for btn in self.TabBtn :
						if btn.id == 7:
							self.DoTheChronometer(btn)
							break
					return 1
			elif event.type == MOUSEBUTTONUP:
				#********************** on relache la souris *******************
				event0 = event.pos[0]
				event1 = event.pos[1]

				const.GMaSourisCurrentPositionX = event0 
				const.GMaSourisCurrentPositionY = event1 

				self.DoOnMouseUpBeforeButtons(event0, event1)

				#---------------- recherche du bouton concerne -----------------
				for btn in self.TabBtn :
					if ( event0 + const.DEMISOURIS >= btn.left ) & ( event0 + const.DEMISOURIS <= btn.left + btn.largeur ) & ( event1 + const.DEMISOURIS >= btn.top  ) & ( event1 + const.DEMISOURIS <= btn.top + btn.hauteur ) :
						if btn.actif == False:
							break

						if ( btn.id == 1 ) :
							#autre mode
							self.DoTheChangeMode()
						elif ( btn.id == 2) :
							#Quitter
							for btn in self.TabBtn :
								if btn.id == 7:
									self.StopChrono(btn)
									break
							return 0
						elif ( btn.id == 3) :
							#image avant (dans le theme)
							self.DoImagePrev()
						elif ( btn.id == 4) :
							#image apres (dans le theme)
							self.DoImageNext()
						elif ( btn.id == 5) :
							#autre theme
							self.DoTheChangeTheme()
						elif ( btn.id == 6) :
							#niveau 
							self.DoTheChangeLevel()
						elif ( btn.id == 7) :
							#chronometre
							self.DoTheChronometer(btn)

						#on sort de la boucle des boutons
						break

				self.DoOnMouseUpAfterButtons(event0, event1)

			elif event.type == MOUSEBUTTONDOWN:
				#******************* enfoncement de la souris ******************
				str = event.button
				event0 = event.pos[0] 
				event1 = event.pos[1] 

#				if self.WaitForClick == True:
#					if pygame.event.peek(MOUSEBUTTONUP) == True:
#						self.DoOnMouseUpAfterButtons(event0, event1)

				self.DoOnMouseDown(event0, event1, str)
#				else:
#					return 1
			elif event.type == MOUSEMOTION:
				#*************** evenement deplacement de la souris ****************
				event0 = event.pos[0]
				event1 = event.pos[1]

				if self.WaitForClick == True:
					if pygame.event.peek(MOUSEBUTTONUP) == True:
						self.DoOnMouseUpAfterButtons(event0, event1)
						continue


				screen = pygame.display.get_surface()

				str = event.buttons 

				#on va voir si on est au dessus d'un bouton de menu
				self.ManageSurvol(event0, event1)

#????				if const.GTypeSouris == const.EVENT_JEU0:
					#on est en mode jeu
				self.MotionBeforeMouse(event0, event1, str)

				#redessin de la souris a sa position actuelle
				const.GMaSourisCurrentPositionX = event0 
				const.GMaSourisCurrentPositionY = event1 
				for o in const.GLstSouris.sprites():
					o.move(self.Background)

				self.MotionAfterMouse(event0, event1, str)

				const.GLstSouris.draw(screen)
				pygame.display.update()

				return 1


			else :
				if self.WaitForClick == True:
					if pygame.event.peek(MOUSEBUTTONUP) == True:
						event0 = event.pos[0]
						event1 = event.pos[1]
						self.DoOnMouseUpAfterButtons(event0, event1)
					else:
						return 1
				else:
					return 1

		return 1

	#***************************************************************************
	#
	#***************************************************************************
	def ReadDfgFile(self):
		datas.DebugMessage("Reading the dfg file number %i named %s " % (self.IdxFileDfg, self.LstFicConfig[self.IdxFileDfg]) )

		#a surcharger par chaque application


	#***************************************************************************
	#
	#***************************************************************************
	def ChangeLevel(self):
		datas.DebugMessage("")
		datas.DebugMessage("Current level : %i" % const.GLevel)

		if const.GLevel == 2:
			#on quitte le niveau difficule donc le mode chronometre ne 
			#doit plus exiter

	#		for obj2 in LstBtn.sprites():
	#			if obj2.id == 7:
	#				LstBtn.remove(obj2)
	#				break
			for btn in self.TabBtn:
				if btn.id == 7 :
	#				btn.LoadNormalPicture()
					self.StopChrono(btn)
					break

#		screen = pygame.display.get_surface()

		const.GLevel += 1
		if const.GLevel > 2 :
			const.GLevel = 0

		#si activite move
#		const.GTailleCarreau = const.GLevel
	
		#si activite 
		datas.DebugMessage("New level : %i " % const.GLevel)

	#	if const.GLevel == 2 :
	#		#on affiche le mode chronometre
	#		LstBtn.add(BtnMenu(750, 220, 'btn-timer-off.png', 7))
	#		const.GChrono = 0
	
	#	filename = os.path.join(const.GRepPysycache, "images", 'level' + str(const.GLevel) + '.png')
	#	obj.imagenametp = filename
	#	obj.image, obj.rect = Load_image("images", filename, 1)
	#	filename = os.path.join(const.GRepPysycache, "images", 'level' + str(const.GLevel) + '-gd.png')
	#	obj.imagenamegd = filename
	#	obj.rect.left = obj.left 
	#	obj.rect.top = obj.top
	
#		self.HideAndShowBtn()

		#transition
		datas.ShowTransitionOfTheme(const.GDureeTransition, 'fond-' + self.ActivityName + '.png')
		
		#rechercher eventuellement les nouveaux fichiers de configuration
		self.SearchAllConfigFiles()

		#lire ce fichier de configuration
		self.ReadDfgFile()

		self.DoInitLevel()

		#mise en place de l'interface du jeu
		self.InitGame(False)

#		self.ShowBtnMenus()

		screen = pygame.display.get_surface()
		const.GLstSouris.draw(screen)
		pygame.display.update()


class BtnOfApplication:
	def __init__(self, background, id, imagenamegd, imagenametp, left = 0, top = 0, largeur = 0, hauteur = 0, actif = False, survol = True, debutsurvol = 0, isrelatif = True, visible = False):
		self.id = id
		self.background = background					#nom du fichier de fond
		self.SecondPicture = imagenamegd				#nom de l'image si survol
		self.NormalPicture = imagenametp				#nom de l'image normal
		self.left = left
		self.top = top
		self.largeur = largeur
		self.hauteur = hauteur
		self.actif = actif						#pour les gros boutons et activer l'evt click (si = 1)
		self.survol = survol						#0 : pas survol
										#1 : survol
		self.debutsurvol = debutsurvol					#heure du debut de survol
		self.isrelatif = isrelatif
		self.visible = visible					#0 : invisible,  1 : visible
#		rectbkg = pygame.Rect([0, 0, 64, 64])

	def ClearBackground(self, background, backgroundclear):
		screen = pygame.display.get_surface()

		#on colle l'ancien arriere plan (pour "effacer")
#		imagetmp, recttmp = datas.Load_image("images", self.background)
		tr2 = pygame.Rect([self.left, self.top, self.largeur, self.hauteur] )
		background.blit(backgroundclear, [self.left, self.top], tr2 )
		screen.blit(background, [self.left, self.top], tr2 )


	def LoadNormalPicture(self, background, backgroundclear):
		screen = pygame.display.get_surface()

		#on colle l'ancien arriere plan (pour "effacer")
		self.ClearBackground(background, backgroundclear)

		#on colle l'image correspondante (la petite)
		imagetmp, recttmp = datas.Load_image("images", self.NormalPicture, None, not self.isrelatif)
		(larg, haut) = imagetmp.get_size()

		if self.largeur * self.hauteur > 0:
			oldleft = self.left
			oldtop = self.top
			oldlargeur = self.largeur
			oldhauteur = self.hauteur
		else:
			oldleft =  self.left
			oldtop = self.top
			oldlargeur = larg
			oldhauteur = haut

		self.largeur = larg
		self.hauteur = haut
		self.left = oldleft + int( ( oldlargeur - self.largeur ) / 2) 
		self.top = oldtop + int( ( oldhauteur - self.hauteur ) / 2) 
		self.survol = 0
		self.debutsurvol = 0
		self.actif = False
		const.GIdBtnSurvol = 99
		background.blit(imagetmp, (self.left, self.top))
		screen.blit(imagetmp, (self.left, self.top))

	def LoadSecondPicture(self, background, backgroundclear, filesound = 'btnmenu.wav'):
		datas.Load_sound("sounds", filesound)

		screen = pygame.display.get_surface()

		#on colle l'ancien arriere plan (pour "effacer")
		self.ClearBackground(background, backgroundclear)

		oldleft = self.left
		oldtop = self.top
		oldlargeur = self.largeur
		oldhauteur = self.hauteur

		#on colle l'image correspondante (la plus grande)
		imagetmp, recttmp = datas.Load_image("images", self.SecondPicture, None, not self.isrelatif)
		(self.largeur, self.hauteur) = imagetmp.get_size()
		self.left = oldleft - int( ( - oldlargeur + self.largeur ) / 2)
		self.top = oldtop - int ( ( - oldhauteur + self.hauteur ) / 2) 
		background.blit(imagetmp, (self.left, self.top))
		screen.blit(imagetmp, (self.left, self.top))

	def ShowHelpOfMenu(self, imgdest):
		myfont = os.path.join(const.GRepPysycache, 'fonts', const.GFontName ).encode(const.GConsoleLocale)
		font = pygame.font.Font(myfont, 20)
		textcolor = 46, 113, 169
		screen = pygame.display.get_surface()

		myrep = os.path.join(const.GRepPysycache, 'lang', const.GMyLocale )

		#joue le fichier d'aide
		if const.GWithSound == 1:
			if const.GWithHelp == 1 :
				dirname = os.path.join(const.GRepPysycache, 'lang', const.GMyLocale)
				filename = 'menu' + str(self.id) + '.ogg'
				datas.Load_sound(dirname, filename)
		
		#affiche l'aide
		if os.path.isdir(myrep):
			filename = os.path.join(const.GRepPysycache, 'lang', const.GMyLocale , 'menu' + str(self.id) + '.txt')
		else :
			filename = os.path.join(const.GRepPysycache, 'lang', 'en_EN' , 'menu' + str(self.id) + '.txt')
			
		filename = os.path.join(const.GRepPysycache, 'lang', const.GMyLocale , 'menu' + str(self.id) + '.txt')
		if os.path.isfile(filename):
			f = open(filename, 'r')
			lignes  = f.readlines()
			cptligne = 0
			for j in lignes:
				j = j.strip()
#				text = font.render(unicode(j, "utf-8"), 1, textcolor)
				text = font.render(j.decode("utf-8", "ignore"), 1, textcolor)
				imgdest.blit(text, (195, 361 + 25 * cptligne))
				screen.blit(text, (195, 361 + 25 * cptligne))

				cptligne += 1
			f.close()

			pygame.display.update()



#*******************************************************************************
#
#*******************************************************************************
class Preferences:
	"""Preference de l'utilisateur """
	def __init__(self):
		self.Sound = 1			#with sound
		self.Lang = ""
		self.Level = 1			#middle
		self.Transition = 5
		self.FullScreen = 1		#plein ecran
		self.LogoFile = ""
		self.Fileofpreference = ""
		self.FontName = ""



	def ReadConfigOfUser(self, filename):
		""" Read the configuration file for the pysycache user"""

		#verification que les repertoires de l'utilisateur existent
		myrep = os.path.join(const.GRepPersoUser, unicode("themes-buttons"))
		if os.path.isdir(myrep) == False:
			os.makedirs(myrep)
		myrep = os.path.join(const.GRepPersoUser, unicode("themes-click"))
		if os.path.isdir(myrep) == False:
			os.makedirs(myrep)
		myrep = os.path.join(const.GRepPersoUser, unicode("themes-move"))
		if os.path.isdir(myrep) == False:
			os.makedirs(myrep)
		myrep = os.path.join(const.GRepPersoUser, unicode("themes-dblclick"))
		if os.path.isdir(myrep) == False:
			os.makedirs(myrep)
		myrep = os.path.join(const.GRepPersoUser, unicode("themes-puzzle"))
		if os.path.isdir(myrep) == False:
			os.makedirs(myrep)

		datas.DebugMessage("")
		datas.DebugMessage("Reading the configuration file of user ( %s )... " % filename )

		#initialisation avec les valeurs par defaut
		self.Sound = 1			#with sound
		self.Lang = ""
		self.Level = 1			#middle
		self.Transition = 5
		self.FullScreen = 1		#plein ecran
		self.LogoFile = ""
		self.Fileofpreference = ""
		self.FontName = ""

		self.Fileofpreference = filename
		datas.DebugMessage("self.Fileofpreference : %s " % self.Fileofpreference )

		#lecture du fichier de configuration de l'utilisateur
		if os.path.isfile(filename):
			f = open(filename, 'r')
			lignes  = f.readlines()
			for lig in lignes:
				lig = lig.strip()
				lig = lig.split('=')

				if len(lig) == 0:
					continue

				if string.upper(lig[0]) == 'FULL' :
					#fullscreen
					self.FullScreen = int(lig[1])

				if string.upper(lig[0]) == 'SND' :
					#sound
					self.Sound = int(lig[1])

				if string.upper(lig[0]) == 'LEVEL' :
					#level of player
					self.Level = int(lig[1])

				if string.upper(lig[0]) == 'LANG' :
					#lang
					self.Lang = lig[1]

				if string.upper(lig[0]) == 'LOGO' :
					#logo
					self.LogoFile = lig[1]

				if string.upper(lig[0]) == 'TRANSIT' :
					#vitesse de transition
					self.Transition = int(lig[1])

			f.close()
		else:
			datas.DebugMessage("")
			datas.DebugMessage("Configuration file for user doesn't exist")

		datas.DebugMessage("")
		datas.DebugMessage("Sound :      %i " % self.Sound)
		datas.DebugMessage("Lang :       %s " % self.Lang)
		datas.DebugMessage("Level :      %i " % self.Level)
		datas.DebugMessage("Transition : %i " % self.Transition)
		datas.DebugMessage("FullScreen : %i " % self.FullScreen)
		datas.DebugMessage("Logo :       %s " % self.LogoFile)

	def Save(self):
		#save the user configuration
		datas.DebugMessage("")
		datas.DebugMessage("Save preferences in file %s " % self.Fileofpreference)

		file = open(self.Fileofpreference,'w')
		file.write("FULL=" + str(self.FullScreen) + "\n")
		file.write("SND=" + str(self.Sound) + "\n")
		file.write("LEVEL=" + str(self.Level) + "\n")
		file.write("LANG=" + self.Lang + "\n")
		file.write("LOGO=" + self.LogoFile + "\n")
		file.write("TRANSIT=" + str(self.Transition) + "\n")
		file.close()
