#!/usr/bin/python
#
# We're using PySide, Nokia's official LGPL bindings.
# You can however easily use PyQt (Riverside Computing's GPL bindings) by commenting these and fixing the appropriate imports.
import sys, os, time, thread
import glib, gobject
import pygst
pygst.require("0.10")
import gst
from ctypes import *
import subprocess
from PySide.QtCore import *
from PySide.QtGui import *
from PySide.QtMaemo5 import QMaemo5ValueButton, QMaemo5InformationBox
import dbus.mainloop.qt
import codecs
 
# In Qt, everything is a class.
# We can subclass stuff to do whatever we want - it seems a bit strange at first,
# but it keeps all related functionality in one place, which helps to keep you organised.
#
# We're subclassing 'QWidget' here. QWidget is the base class for all graphical elements in Qt.
# You can do all sorts of cool things like drawing your widget yourself, but we won't get into that.
#
# See also:
#   http://doc.trolltech.com/4.6/qwidget.html

####################
# Global variables #
####################
CooktimerVersion = "0.0.4-5"
Vibration = False
Sound = False
Wakeup = False
Alarmbanner = False
Backlight = False
Volume = 50
defaultVolume = 50
Orientation = "Auto"
Home = os.path.expanduser("~")
CommentChar = '#'
OptionChar =  ' '
Cooktimer_CfgDir = Home + '/.config/cooktimer/'
Cooktimer_CfgFile = Cooktimer_CfgDir + 'cooktimer.cfg'
Cooktimer_ItemFile = Cooktimer_CfgDir + 'cooktimer.items'
Cooktimer_StartItems = Cooktimer_CfgDir + 'cooktimer.start-items'
Language = os.getenv('LANG')
hoursPicked0 = "00"
minutesPicked0 = "00"
secondsPicked0 = "00"
hoursPicked1 = "00"
minutesPicked1 = "00"
secondsPicked1 = "00"
hoursPicked2 = "00"
minutesPicked2 = "00"
secondsPicked2 = "00"
hoursPicked3 = "00"
minutesPicked3 = "00"
secondsPicked3 = "00"
dishName1 = ""
dishName1banner = ""
dishPicked1Nbr = ""
dishName2 = ""
dishName2banner = ""
dishPicked2Nbr = ""
dishName3 = ""
dishName3banner = ""
dishPicked3Nbr = ""
rowNbr=1
msgTxtPicked1_1 = ""
msgTimePicked1_1 = ""
msgTxtPicked1_2 = ""
msgTimePicked1_2 = ""
msgTxtPicked1_3 = ""
msgTimePicked1_3 = ""
msgTxtPicked2_1 = ""
msgTimePicked2_1 = ""
msgTxtPicked2_2 = ""
msgTimePicked2_2 = ""
msgTxtPicked2_3 = ""
msgTimePicked2_3 = ""
msgTxtPicked3_1 = ""
msgTimePicked3_1 = ""
msgTxtPicked3_2 = ""
msgTimePicked3_2 = ""
msgTxtPicked3_3 = ""
msgTimePicked3_3 = ""
pause1 = False
pause2 = False
pause3 = False
currSelector = 0
playstate = 2
Playbin2 = gst.element_factory_make("playbin2", "player")
Alarmfile = "/opt/cooktimer/alarm-cooktimer.wav"
hPath = ""

##########################################
# gstreamer stuff to play in silent mode #
# used concept from Faheem Pervez        #
##########################################
pulse_lib = CDLL("libpulse-mainloop-glib.so.0")
gobject_lib = CDLL("libgobject-2.0.so.0")

g_object_set = gobject_lib.g_object_set

class PA_PROPLIST(Structure):
  _fields_ = [("_opaque_struct", c_int)]

# pa_proplist_*
pa_proplist_new = pulse_lib.pa_proplist_new
pa_proplist_new.restype = POINTER(PA_PROPLIST)
pa_proplist_new.argtypes = [ ]

pa_proplist_sets = pulse_lib.pa_proplist_sets
pa_proplist_sets.restype = c_int
pa_proplist_sets.argtypes = [
        POINTER(PA_PROPLIST),
        c_char_p,
        c_char_p
]

pa_proplist_free = pulse_lib.pa_proplist_free
pa_proplist_sets.restype = None
pa_proplist_sets.argtypes = [
        POINTER(PA_PROPLIST),
]


def parse_config(self, filename):
	options = {}
	f = codecs.open(filename,"r","utf-8")
	for line in f:
		# First, remove comments:
		if CommentChar in line:
			# split on comment char, keep only the part before
			line, comment = line.split(CommentChar, 1)
		# Second, find lines with an option=value:
		if OptionChar in line:
			# split on option char:
			option, value = line.split(OptionChar, 1)
			# strip spaces:
			option = option.strip()
			value = value.strip()
			# store in dictionary:
			options[option] = value
	f.close()
 	return options

def load_dishes(self):
	global OptionChar
	OptionChar = "|"
	cooktimer_items = parse_config(self,Cooktimer_ItemFile)
	DishList = ""
	# make a new list for sorting case-insensitive
	for item in cooktimer_items:
		DishList = DishList + item + '|' + cooktimer_items[item] + "\n"
	contentsList = DishList.split('\n')
	contentsList = contentsList[:-1]
	contentsList.sort(lambda a, b: cmp(a.upper(), b.upper()))
	# initialize array
	dishes = []
	for dish in contentsList:
		item, value  = dish.split(OptionChar,1)
		dishes.append([item,value])
	return dishes

def Alarm(self):
	global playstate
	if Wakeup:
		# Switch on backlight to be sure message is displayed
		strUnlock = "dbus-send --print-reply --system --dest=com.nokia.mce /com/nokia/mce/request com.nokia.mce.request.req_tklock_mode_change string:unlocked"
		QProcess.startDetached(strUnlock)
	if Vibration:
		os.system('dbus-send --system --print-reply --dest=com.nokia.mce /com/nokia/mce/request com.nokia.mce.request.req_start_manual_vibration int32:250 int32:3000')
	if Sound:
			bus = dbus.SessionBus()
			obj = bus.get_object("com.nokia.mafw.renderer.Mafw-Gst-Renderer-Plugin.gstrenderer",
				"/com/nokia/mafw/renderer/gstrenderer")
			state = dbus.Interface(obj, "com.nokia.mafw.renderer")
			playlist, index, playstate, object_id = state.get_status()
			if playstate == 1:
				# Stopped = 0 Playing = 1 Paused = 2 Transitioning = 3
				os.popen("dbus-send --dest=com.nokia.mafw.renderer.Mafw-Gst-Renderer-Plugin.gstrenderer /com/nokia/mafw/renderer/gstrenderer com.nokia.mafw.renderer.pause")
			os.system("dbus-send --type=method_call --dest=com.nokia.mafw.renderer.Mafw-Gst-Renderer-Plugin.gstrenderer /com/nokia/mafw/renderer/gstrenderer \
				com.nokia.mafw.extension.set_extension_property string:volume variant:uint32:"+str(Volume))
			# use workaround for silent profile
			mainclass = Gstreamer_play()
			thread.start_new_thread(mainclass.start, ())
			gobject.threads_init()

def printMsg(self,message,duration):
        box = QMaemo5InformationBox()
        box.information(self, message, duration)
        box.show()

def format_seconds_to_hhmmss(seconds):
	hours = seconds // (60*60)
	seconds %= (60*60)
	minutes = seconds // 60
	seconds %= 60
	return "%02i:%02i:%02i" % (hours, minutes, seconds)


class MyMainWindow(QMainWindow):
	def __init__(self, parent=None):# first things first, we need to initialise the Qt parent, otherwise it won't work properly.
		#
		super(MyMainWindow, self).__init__(parent)
		self.setAttribute(Qt.WA_Maemo5StackedWindow)
		global Orientation
		global defaultVolume
		self.setWindowTitle(self.tr("cooktimer"))
		# catch dbus signal for keyboard slider
		dbus.mainloop.qt.DBusQtMainLoop(set_as_default=True)
		bus = dbus.SystemBus()
		bus.add_signal_receiver(self.handle_slide, path='/org/freedesktop/Hal/devices/platform_slide', dbus_interface='org.freedesktop.Hal.Device', signal_name='PropertyModified')

		# store current volume
		bus = dbus.SessionBus()
		obj = bus.get_object("com.nokia.mafw.renderer.Mafw-Gst-Renderer-Plugin.gstrenderer", "/com/nokia/mafw/renderer/gstrenderer")
		mafw = dbus.Interface(obj, "com.nokia.mafw.extension")
		defaultVolume = int(mafw.get_extension_property("volume")[1])
		# Create config dir if needed
		if not os.path.exists(Cooktimer_CfgDir):
			os.mkdir(Cooktimer_CfgDir)
		# Create config files if needed
		if not os.path.isfile(Cooktimer_CfgFile):
			try:
				newConfigFile = open(Cooktimer_CfgFile,"w")
			except:
				QMessageBox.critical(self, "Warning",  "Cannot write " + Cooktimer_CfgFile)
			else:
				newConfigFile.write("keepbacklighton true\n")
				newConfigFile.write("vibration true\n")
				newConfigFile.write("wakeup true\n")
				newConfigFile.write("orientation auto\n")
				newConfigFile.write("sound true\n")
				newConfigFile.write("volumelevel 50\n")
				newConfigFile.write("alarmfile /opt/cooktimer/alarm-cooktimer.wav\n")
				newConfigFile.write("alarmbanner true\n")
				newConfigFile.close()
		else:
			keepbacklightset = False
			vibrationset = False
			wakeupset = False
			soundset = False
			volsoundset = False
			orientationset = False
			alarmfileset = False
			alarmbannerset = False
			ConfigFile = open(Cooktimer_CfgFile,"r")
			lines = ConfigFile.readlines()
			for line in lines:
				if 'keepbacklighton' in line:
					keepbacklightset = True
				if 'vibration' in line:
					vibrationset = True
				if 'wakeup' in line:
					wakeupset = True
				if 'sound' in line:
					soundset = True
				if 'volumelevel' in line:
					volsoundset = True
				if 'orientation' in line:
					orientationset = True
				if 'alarmfile' in line:
					alarmfileset = True
				if 'alarmbanner' in line:
					alarmbannerset = True
			ConfigFile.close()
			if not keepbacklightset or not vibrationset or not wakeupset or not soundset or not volsoundset \
			or not orientationset or not alarmfileset or not alarmbannerset:
				ConfigFile = open(Cooktimer_CfgFile,"a")
				if not keepbacklightset:
					ConfigFile.write("keepbacklighton true\n")
				if not vibrationset:
					ConfigFile.write("vibration true\n")
				if not wakeupset:
					ConfigFile.write("wakeup true\n")
				if not soundset:
					ConfigFile.write("sound true\n")
				if not volsoundset:
					ConfigFile.write("volumelevel 50\n")
				if not orientationset:
					ConfigFile.write("orientation auto\n")
				if not alarmfileset:
					ConfigFile.write("alarmfile /opt/cooktimer/alarm-cooktimer.wav\n")
				if not alarmbannerset:
					ConfigFile.write("alarmbanner true\n")
				ConfigFile.close()

		if not os.path.isfile(Cooktimer_ItemFile):
			try:
				newConfigFile = open(Cooktimer_ItemFile,"w")
			except:
				QMessageBox.critical(self, "Warning",  "Cannot write " + Cooktimer_ItemFile)
			else:
				newConfigFile.close()

		if not os.path.isfile(Cooktimer_StartItems):
			try:
				newItemstartupFile = open(Cooktimer_StartItems,"w")
			except:
				QMessageBox.critical(self, "Warning",  "Cannot write " + Cooktimer_StartItems)
			else:
				newItemstartupFile.close()

		###############
		# read config #
		###############
		global OptionChar
		global Alarmfile
		global Alarmbanner
		global Wakeup
		global Vibration
		global Backlight
		global Volume
		global Sound
		OptionChar = " "
		self.cooktimer_opts = parse_config(self,Cooktimer_CfgFile)
		Alarmfile = self.cooktimer_opts["alarmfile"]
		Volume = self.cooktimer_opts["volumelevel"]
		###############
		# Create menu #
		###############
		orientationGroup = QActionGroup(self)
		orientationGroup.setExclusive(True)
		self.landscapeAction = QAction( '&Landscape' ,self)
		self.landscapeAction.setCheckable(True)
		self.portraitAction = QAction( '&Portrait' ,self)
		self.portraitAction.setCheckable(True)
		self.autorotateAction = QAction( '&Autorotate' ,self)
		self.autorotateAction.setCheckable(True)
		orientationGroup.addAction(self.landscapeAction)
		orientationGroup.addAction(self.autorotateAction)
		orientationGroup.addAction(self.portraitAction)
		
		self.configAction = QAction( '&Settings', self)
		if self.cooktimer_opts["keepbacklighton"] == "true":
			Backlight = True
		if self.cooktimer_opts["wakeup"] == "true":
			Wakeup = True
		if self.cooktimer_opts["vibration"] == "true":
			Vibration = True
		if self.cooktimer_opts["sound"] == "true":
			Sound = True
		self.orientationAction = QAction( '', self)
		if self.cooktimer_opts["orientation"] == "portrait":
			self.portraitAction.setChecked(True)
			self.setAttribute(Qt.WA_Maemo5PortraitOrientation, True)
			Orientation = "portrait"
		elif self.cooktimer_opts["orientation"] == "landscape":
			self.landscapeAction.setChecked(True)
			self.setAttribute(Qt.WA_Maemo5LandscapeOrientation, True)
			Orientation = "landscape"
		else:
			self.autorotateAction.setChecked(True)
			self.setAttribute(Qt.WA_Maemo5AutoOrientation, True)
			Orientation = "auto"
		if self.cooktimer_opts["alarmbanner"] == "true":
			Alarmbanner = True
		editAction = QAction( '&Edit dishes', self)
		self.alarmfileAction = QAction( '&Custom WAV alarm', self)
		aboutAction = QAction( '&About', self)

		########################
		# create menu from bar #
		########################
		menubar = self.menuBar()
		mainMenu = menubar.addMenu('&MainMenu')
		mainMenu.addActions(orientationGroup.actions())
		mainMenu.addAction(self.configAction)
		mainMenu.addAction(self.alarmfileAction)
		mainMenu.addAction(editAction)
		mainMenu.addAction(aboutAction)

		##################
		# Define actions #
		##################
		self.alarmfileAction.triggered.connect(self.alarmfilePushed)
		self.portraitAction.triggered.connect(self.portraitPushed)
		self.landscapeAction.triggered.connect(self.landscapePushed)
		self.autorotateAction.triggered.connect(self.autorotatePushed)
		editAction.triggered.connect(self.editPushed)
		aboutAction.triggered.connect(self.aboutPushed)
		self.configAction.triggered.connect(self.slotConfig)
		self.connect(self, SIGNAL("didSomething"), self.checkIsDim)

		#############################
		# Prevent backlight dimming #
		#############################
		self.dimtimer = QTimer()
		self.dimtimer.timeout.connect(self.KeepBackLightOn)
		# get timeout value
		self.screendim_timeout = (int(os.popen('gconftool-2 --get /system/osso/dsm/display/display_dim_timeout').read())-1)*1000
		if Backlight:
			self.dimtimer.start(self.screendim_timeout)
		################################################################
		# set initial orientation to landscape if kb open and portrait #
		################################################################
		kb_state = os.popen('cat /sys/devices/platform/gpio-switch/slide/state').read().strip()
		if kb_state == "open" and self.cooktimer_opts["orientation"] == "portrait":
			self.setAttribute(Qt.WA_Maemo5LandscapeOrientation, True)

		self.form_widget = FormWidget(self)
		self.setCentralWidget(self.form_widget)

	def slotConfig(self):
		# show config screen
		a = ConfigWindow(self)
		self.connect(a, SIGNAL("destroyed()"),self.checkIsDim)
		a.show()

	def checkIsDim(self):
		if Backlight and not self.dimtimer.isActive():
			self.dimtimer.start(self.screendim_timeout)
		if not Backlight and self.dimtimer.isActive():
			self.dimtimer.stop()

	def handle_slide(self,var1,var2):
		kb_state = os.popen('cat /sys/devices/platform/gpio-switch/slide/state').read().strip()
		if kb_state == "open" and Orientation == "portrait":
			self.setAttribute(Qt.WA_Maemo5LandscapeOrientation, True)
		elif Orientation == "portrait":
			self.setAttribute(Qt.WA_Maemo5PortraitOrientation, True)
		
	def KeepBackLightOn(self):
		strUnlock = "dbus-send --system --type=method_call --dest=com.nokia.mce /com/nokia/mce/request com.nokia.mce.request.req_display_blanking_pause"
		QProcess.startDetached(strUnlock)

	def saveSettings(self):
		global OptionChar
		OptionChar = " "
		self.cooktimer_opts = parse_config(self,Cooktimer_CfgFile)
		if Vibration:
			self.cooktimer_opts["vibration"] = "true"
		else: self.cooktimer_opts["vibration"] = "false"
		if Backlight:
			self.cooktimer_opts["keepbacklighton"] = "true"
		else: self.cooktimer_opts["keepbacklighton"] = "false"
		if Wakeup:
			self.cooktimer_opts["wakeup"] = "true"
		else: self.cooktimer_opts["wakeup"] = "false"
		if Sound:
			self.cooktimer_opts["sound"] = "true"
		else: self.cooktimer_opts["sound"] = "false"
		if self.portraitAction.isChecked():
			self.cooktimer_opts["orientation"] = "portrait"
			Orientation = "portrait"
		if self.landscapeAction.isChecked():
			self.cooktimer_opts["orientation"] = "landscape"
			Orientation = "landscape"
		if self.autorotateAction.isChecked():
			self.cooktimer_opts["orientation"] = "auto"
			Orientation = "auto"
		if Alarmbanner:
			self.cooktimer_opts["alarmbanner"] = "true"
		else: self.cooktimer_opts["alarmbanner"] = "false"
		self.cooktimer_opts["volumelevel"] = str(Volume)
		self.cooktimer_opts["alarmfile"] = Alarmfile
		try:
			newConfigFile = open(Cooktimer_CfgFile,"w")
			for option in self.cooktimer_opts:
				newConfigFile.write(option + " " + self.cooktimer_opts[option] + "\n")
			newConfigFile.close()
			os.system('run-standalone.sh dbus-send --type=method_call --dest=org.freedesktop.Notifications  \
				/org/freedesktop/Notifications org.freedesktop.Notifications.SystemNoteInfoprint \
				string:"Configuration is successfully saved"')
		except:
			os.system('run-standalone.sh dbus-send --type=method_call --dest=org.freedesktop.Notifications  \
				/org/freedesktop/Notifications org.freedesktop.Notifications.SystemNoteInfoprint \
				string:"Could NOT save Configuration!"')

	def alarmfilePushed(self):
		widget = fileWindow(self)
		widget.show()

	def portraitPushed(self):
		if self.cooktimer_opts["orientation"] != "portrait":
			self.setAttribute(Qt.WA_Maemo5PortraitOrientation, True)
			Orientation = "portrait"
			self.saveSettings()
	
	def landscapePushed(self):
		if self.cooktimer_opts["orientation"] != "landscape":
			self.setAttribute(Qt.WA_Maemo5LandscapeOrientation, True)
			Orientation = "landscape"
			self.saveSettings()

	def autorotatePushed(self):
		if self.cooktimer_opts["orientation"] != "auto":
			self.setAttribute(Qt.WA_Maemo5AutoOrientation, True)
			Orientation = "auto"
			self.saveSettings()

	def editPushed(self):
		widget = itemWindow(self)
		widget.show()

	def aboutPushed(self):
		d = QDialog(self)
		vbox = QVBoxLayout()
		verticalLayout = QVBoxLayout() 
		d.setWindowTitle(self.tr("About cooktimer"))
		verticalLayout.addWidget(QLabel("<center><img src=/opt/usr/share/icons/hicolor/64x64/apps/cooktimer.png /></center>"),0)
		verticalLayout.addWidget(QLabel("<center><b><big>Cooktimer "+CooktimerVersion+"<big></b></center>"),1)
		verticalLayout.addWidget(QLabel("<center>Created by Arno Dekker (ade)</center><br>"),2)
		vbox.addLayout (verticalLayout)
		d.setLayout(vbox)
		d.show()

class ConfigWindow(QMainWindow):
	def __init__(self,parent):
		QMainWindow.__init__(self,parent)
		self.setWindowTitle("Configuration cooktimer")
		self.setAttribute(Qt.WA_Maemo5StackedWindow)
		self.setAttribute(Qt.WA_DeleteOnClose)
		area = QScrollArea()
		lay = QVBoxLayout()
		lay.addWidget(area)
		self.wg = QWidget()
		area.setWidget(self.wg)
		self.setCentralWidget(area)
		self.grid = QGridLayout(self.wg)
		self.wg.show()
		area.show()
		self.setLayout(self.grid)
		# define checkboxes
		self.backlightCheckbox = QCheckBox("Keep backlight on",self)
		self.backlightCheckbox.setMinimumWidth(370)
		self.screenwakeupCheckbox = QCheckBox("Wakeup screen on alarm",self)
		self.vibrateCheckbox = QCheckBox("Vibrate on alarm",self)
		self.soundCheckbox = QCheckBox("Sound on alarm",self)
		self.bannerCheckbox = QCheckBox("Alarm banner",self)
		self.volSlider = QSlider(Qt.Horizontal, self)
		self.volLabel = QLabel("<center><i>Alarm volume</i></center>")
		self.volLabel.setMaximumHeight(60)
		self.volSlider.setMinimum(0);
		self.volSlider.setMaximum(100);
		self.volSlider.setValue(int(Volume))
		# set checked/unchecked
		if Backlight:
			self.backlightCheckbox.setChecked(True)
		if Wakeup:
			self.screenwakeupCheckbox.setChecked(True)
		if Vibration:
			self.vibrateCheckbox.setChecked(True)
		if Sound:
			self.soundCheckbox.setChecked(True)
		if Alarmbanner:
			self.bannerCheckbox.setChecked(True)
		self.saveConfigButton = QPushButton("Done",self)
		self.saveConfigButton.setMinimumHeight(80)
		self.saveConfigButton.setStyleSheet("QPushButton { font:bold; }")
		# set correct layout
		self.orientationChanged()
		# signals
		self.connect(self.saveConfigButton, SIGNAL("clicked()"),self.saveConfig)
		self.connect(QApplication.desktop(), SIGNAL("resized(int)"), self.orientationChanged)

	def saveSettings(self):
		global OptionChar
		OptionChar = " "
		self.cooktimer_opts = parse_config(self,Cooktimer_CfgFile)
		if Vibration:
			self.cooktimer_opts["vibration"] = "true"
		else: self.cooktimer_opts["vibration"] = "false"
		if Backlight:
			self.cooktimer_opts["keepbacklighton"] = "true"
		else: self.cooktimer_opts["keepbacklighton"] = "false"
		if Wakeup:
			self.cooktimer_opts["wakeup"] = "true"
		else: self.cooktimer_opts["wakeup"] = "false"
		if Sound:
			self.cooktimer_opts["sound"] = "true"
		else: self.cooktimer_opts["sound"] = "false"
		self.cooktimer_opts["orientation"] = Orientation
		if Alarmbanner:
			self.cooktimer_opts["alarmbanner"] = "true"
		else: self.cooktimer_opts["alarmbanner"] = "false"
		self.cooktimer_opts["volumelevel"] = str(Volume)
		self.cooktimer_opts["alarmfile"] = Alarmfile
		try:
			newConfigFile = open(Cooktimer_CfgFile,"w")
			for option in self.cooktimer_opts:
				newConfigFile.write(option + " " + self.cooktimer_opts[option] + "\n")
			newConfigFile.close()
			os.system('run-standalone.sh dbus-send --type=method_call --dest=org.freedesktop.Notifications  \
				/org/freedesktop/Notifications org.freedesktop.Notifications.SystemNoteInfoprint \
				string:"Configuration is successfully saved"')
		except:
			os.system('run-standalone.sh dbus-send --type=method_call --dest=org.freedesktop.Notifications  \
				/org/freedesktop/Notifications org.freedesktop.Notifications.SystemNoteInfoprint \
				string:"Could NOT save Configuration!"')
		self.emit(SIGNAL("didSomething"))
		self.close()

	def saveConfig(self):
		global Wakeup
		global Vibration
		global Sound
		global Alarmbanner
		global Backlight
		global Volume
		if self.screenwakeupCheckbox.isChecked():
			Wakeup = True
		else: Wakeup = False
		if self.bannerCheckbox.isChecked():
			Alarmbanner = True
		else: Alarmbanner = False
		if self.soundCheckbox.isChecked():
			Sound = True
		else: Sound = False
		if self.vibrateCheckbox.isChecked():
			Vibration = True
		else: Vibration = False
		if self.backlightCheckbox.isChecked():
			Backlight = True
		else: Backlight = False
		Volume = self.volSlider.value()
		self.saveSettings()

	def orientationChanged(self):
		screenGeometry = QApplication.desktop().screenGeometry()
		if screenGeometry.width() > screenGeometry.height():
			# landscape
			self.wg.resize(780,300)
			self.wg.setMinimumHeight(420)
			self.wg.setMaximumHeight(420)
			# first remove layout
			self.grid.removeWidget(self.backlightCheckbox)
			self.grid.removeWidget(self.screenwakeupCheckbox)
			self.grid.removeWidget(self.vibrateCheckbox)
			self.grid.removeWidget(self.soundCheckbox)
			self.grid.removeWidget(self.bannerCheckbox)
			self.grid.removeWidget(self.volLabel)
			self.grid.removeWidget(self.volSlider)
			self.grid.removeWidget(self.saveConfigButton)
			# then add again
			self.grid.addWidget(self.backlightCheckbox,1,0)
			self.grid.addWidget(self.screenwakeupCheckbox,1,1)
			self.grid.addWidget(self.vibrateCheckbox,2,0)
			self.grid.addWidget(self.soundCheckbox,2,1)
			self.grid.addWidget(self.bannerCheckbox,3,0)
			self.grid.addWidget(self.volLabel,3,1)
			self.grid.addWidget(self.volSlider,4,0,1,2)
			self.grid.addWidget(self.saveConfigButton,5,0,1,2)
		else:
			# portrait
			self.wg.resize(470,680)
			self.wg.setMinimumHeight(740)
			self.wg.setMaximumHeight(740)
			# first remove layout
			self.grid.removeWidget(self.backlightCheckbox)
			self.grid.removeWidget(self.screenwakeupCheckbox)
			self.grid.removeWidget(self.vibrateCheckbox)
			self.grid.removeWidget(self.soundCheckbox)
			self.grid.removeWidget(self.bannerCheckbox)
			self.grid.removeWidget(self.volSlider)
			self.grid.removeWidget(self.volLabel)
			self.grid.removeWidget(self.saveConfigButton)
			# then add again
			self.grid.addWidget(self.backlightCheckbox,1,0)
			self.grid.addWidget(self.screenwakeupCheckbox,2,0)
			self.grid.addWidget(self.vibrateCheckbox,3,0)
			self.grid.addWidget(self.soundCheckbox,4,0)
			self.grid.addWidget(self.bannerCheckbox,5,0)
			self.grid.addWidget(self.volLabel,6,0)
			self.grid.addWidget(self.volSlider,7,0)
			self.grid.addWidget(self.saveConfigButton,8,0)


class itemWindow(QMainWindow):
	def __init__(self,parent):
		QMainWindow.__init__(self,parent)
		if Language == "nl_NL":
			self.setWindowTitle("Gerecht kooktijden")
		else:
			self.setWindowTitle("Dish cooktimes")
		self.setAttribute(Qt.WA_Maemo5StackedWindow)
		self.setAttribute(Qt.WA_DeleteOnClose)
		self.wg = QWidget(self)

		# create a scroll area for the modules to load
		global OptionChar
		self.grid2 = QGridLayout()
		grid = QGridLayout()
		scrollingWidget = QWidget()
		scrollingWidget.setLayout(self.grid2)
		 
		self.myScrollArea = QScrollArea()
		self.myScrollArea.setWidgetResizable(True)
		self.myScrollArea.setEnabled(True)
		 
		self.myScrollArea.setWidget(scrollingWidget)
		hbox = QGridLayout()
		hbox.addWidget(self.myScrollArea,0,0,1,2)
		 
		self.wg.setMinimumHeight(1050)
		self.wg.setMaximumHeight(1050)
		# Layout
		grid = QGridLayout()
		self.wg.setLayout(hbox)
		self.grid2.setColumnMinimumWidth(0,150)
		grid.setHorizontalSpacing(0)
		grid.setVerticalSpacing(0)
		if Language == "nl_NL":
			self.addItemButton = QPushButton("Nieuw",self)
			self.saveItemButton = QPushButton("Gereed",self)
		else:
			self.saveItemButton = QPushButton("Done",self)
			self.addItemButton = QPushButton("New",self)
		hbox.addWidget(self.addItemButton,17,0)
		hbox.addWidget(self.saveItemButton,17,1)
		OptionChar =  '|'
		cooktimer_items = parse_config(self,Cooktimer_ItemFile)
		self.maxLen=25
		self.teller=1
		self.var_num=1
		DishList = ""
		# make a new list for sorting case-insensitive
		for item in cooktimer_items:
			DishList = DishList + item + '|' + cooktimer_items[item] + "\n"
		contentsList = DishList.split('\n')
		contentsList = contentsList[:-1]
		contentsList.sort(lambda a, b: cmp(a.upper(), b.upper()))
		self.signalMapper = QSignalMapper(self) 
		for dish in contentsList:
			item, value  = dish.split('|',1)
			hh_mi_ss = cooktimer_items[item][:8].split(':',2)
			hh = hh_mi_ss[0]
			mi = hh_mi_ss[1]
			ss = hh_mi_ss[2]
			globals()['ItemName%s' % self.var_num] = QLineEdit(item)
			globals()['ItemName%s' % self.var_num].setMaxLength(self.maxLen)
			self.grid2.addWidget(globals()['ItemName%s' % self.var_num],self.teller,0)
			if Language == "nl_NL":
				globals()['timeSel%s' % self.var_num] = QMaemo5ValueButton("tijd")
			else:
				globals()['timeSel%s' % self.var_num] = QMaemo5ValueButton("time")
			globals()['timeSel%s' % self.var_num].setValueLayout(QMaemo5ValueButton.ValueUnderTextCentered)
			globals()['timeSel%s' % self.var_num].setValueText(hh+":"+mi+":"+ss)
			globals()['timeSel%s' % self.var_num].setStatusTip(cooktimer_items[item])
			self.grid2.addWidget(globals()['timeSel%s' % self.var_num], self.teller, 1)
			self.signalMapper.setMapping(globals()['timeSel%s' % self.var_num],str(self.var_num))
			self.connect(globals()['timeSel%s' % self.var_num], SIGNAL("clicked()"), self.signalMapper, SLOT("map()"))

			globals()['addButton%s' % self.var_num] = QPushButton()
			globals()['addButton%s' % self.var_num].setIcon(QIcon.fromTheme("general_add"))
			globals()['addButton%s' % self.var_num].setStyleSheet("background: transparent; border: none")
			self.grid2.addWidget(globals()['addButton%s' % self.var_num], self.teller, 2)
			self.signalMapper.setMapping(globals()['addButton%s' % self.var_num],-self.var_num)
			self.connect(globals()['addButton%s' % self.var_num], SIGNAL("clicked()"), self.signalMapper, SLOT("map()"))

			globals()['clearButton%s' % self.var_num] = QPushButton()
			globals()['clearButton%s' % self.var_num].setIcon(QIcon.fromTheme("general_close"))
			globals()['clearButton%s' % self.var_num].setStyleSheet("background: transparent; border: none")
			self.grid2.addWidget(globals()['clearButton%s' % self.var_num], self.teller, 3)
			self.signalMapper.setMapping(globals()['clearButton%s' % self.var_num],self.var_num)
			self.connect(globals()['clearButton%s' % self.var_num], SIGNAL("clicked()"), self.signalMapper, SLOT("map()"))

			self.teller +=1
			self.var_num +=1


		self.connect(self.signalMapper, SIGNAL("mapped(int)"), self.Clear)
		self.connect(self.signalMapper, SIGNAL("mapped(const QString &)"), self.TimeSel)

		self.connect(QApplication.desktop(), SIGNAL("resized(int)"), self.orientationChanged)
		self.connect(self.addItemButton, SIGNAL("clicked()"),self.Additems)
		self.connect(self.saveItemButton, SIGNAL("clicked()"),self.Saveitems)

		self.wg.show()
		self.orientationChanged()

	def Clear(self,waarde):
		# waarde equals rownbr
		if waarde < 0:
			global rowNbr
			rowNbr = abs(waarde)
			widget = extItemWindow(self)
			widget.show()
		else:
			globals()['ItemName%s' % waarde].clear()
			globals()['timeSel%s' % waarde].setValueText("00:00:00")
			globals()['ItemName%s' % waarde].hide()
			globals()['timeSel%s' % waarde].hide()
			globals()['addButton%s' % waarde].hide()
			globals()['clearButton%s' % waarde].hide()

	def TimeSel(self,waarde):
		global secondsPicked0
		global minutesPicked0
		global hoursPicked0
		global currSelector

		currSelector = 0
		hh_mi_ss = globals()['timeSel%s' % waarde].valueText().split(':',2)
		hoursPicked0 = hh_mi_ss[0]
		minutesPicked0 = hh_mi_ss[1]
		secondsPicked0 = hh_mi_ss[2]

		timePick = TimePickDialog(self)
		timePick.show()  
		hours = '%02d' % int(hoursPicked0)
		minutes = '%02d' % int(minutesPicked0)
		seconds = '%02d' % int(secondsPicked0)
		timestring = hours + ":" + minutes + ":" + seconds
		globals()['timeSel%s' % waarde].setValueText(timestring)

	def orientationChanged(self):
		screenGeometry = QApplication.desktop().screenGeometry()
		if screenGeometry.width() > screenGeometry.height():
			# landscape
			self.wg.resize(800,362)
			self.wg.setMinimumHeight(440)
			self.wg.setMaximumHeight(440)
			self.myScrollArea.resize(800,362)
			self.myScrollArea.setMinimumHeight(362)
			self.myScrollArea.setMaximumHeight(362)
		else:
			# portrait
			self.wg.resize(480,675)
			self.wg.setMinimumHeight(755)
			self.wg.setMaximumHeight(755)
			self.myScrollArea.resize(480,675)
			self.myScrollArea.setMaximumHeight(675)
			self.myScrollArea.setMinimumHeight(675)

	def Saveitems(self):
		try:
			newItemFile = codecs.open(Cooktimer_ItemFile,"w", encoding="utf-8")
		except:
			QMessageBox.critical(self, "Warning",  "Cannot write " + Cooktimer_ItemFile)	
		else:
			for count in range(1,self.teller):
				allInfo = globals()['timeSel%s' % count].statusTip().split('|')
				itemtxt = globals()['timeSel%s' % count].valueText()
				if len(allInfo) > 1:
					msgTxt1 = allInfo[1]
					msgTime1 = allInfo[2].strip()
					itemtxt = itemtxt + '|' + msgTxt1 + '|' + msgTime1
				if len(allInfo) > 3:
					msgTxt2 = allInfo[3]
					msgTime2 = allInfo[4].strip()
					itemtxt = itemtxt + '|' + msgTxt2 + '|' + msgTime2
				if len(allInfo) > 5:
					msgTxt3 = allInfo[5]
					msgTime3 = allInfo[6].strip()
					itemtxt = itemtxt + '|' + msgTxt3 + '|' + msgTime3
				if globals()['ItemName%s' % count ].text() != "":
					newItemFile.write(globals()['ItemName%s' % count ].text() + "|" + \
					itemtxt + "\n")
			newItemFile.close()
			os.system('run-standalone.sh dbus-send --type=method_call --dest=org.freedesktop.Notifications  \
				/org/freedesktop/Notifications org.freedesktop.Notifications.SystemNoteInfoprint \
				string:"Items are successfully saved"')
		self.close()

	def Additems(self):
		globals()['ItemName%s' % self.var_num] = QLineEdit()
		globals()['ItemName%s' % self.var_num].setMaxLength(self.maxLen)
		self.grid2.addWidget(globals()['ItemName%s' % self.var_num],self.teller,0)
		if Language == "nl_NL":
			globals()['timeSel%s' % self.var_num] = QMaemo5ValueButton("tijd")
		else:
			globals()['timeSel%s' % self.var_num] = QMaemo5ValueButton("time")
		globals()['timeSel%s' % self.var_num].setValueLayout(QMaemo5ValueButton.ValueUnderTextCentered)
		globals()['timeSel%s' % self.var_num].setValueText("00:00:00")
		self.grid2.addWidget(globals()['timeSel%s' % self.var_num], self.teller, 1)
		self.signalMapper.setMapping(globals()['timeSel%s' % self.var_num],str(self.var_num))
		self.connect(globals()['timeSel%s' % self.var_num], SIGNAL("clicked()"), self.signalMapper, SLOT("map()"))
		globals()['addButton%s' % self.var_num] = QPushButton()
		globals()['addButton%s' % self.var_num].setIcon(QIcon.fromTheme("general_add"))
		globals()['addButton%s' % self.var_num].setStyleSheet("background: transparent; border: none")
		self.grid2.addWidget(globals()['addButton%s' % self.var_num], self.teller, 2)
		globals()['addButton%s' % self.var_num].setEnabled(False)
		self.signalMapper.setMapping(globals()['addButton%s' % self.var_num],-self.var_num)
		self.connect(globals()['addButton%s' % self.var_num], SIGNAL("clicked()"), self.signalMapper, SLOT("map()"))
		globals()['clearButton%s' % self.var_num] = QPushButton()
		globals()['clearButton%s' % self.var_num].setIcon(QIcon.fromTheme("general_close"))
		globals()['clearButton%s' % self.var_num].setStyleSheet("background: transparent; border: none")
		self.grid2.addWidget(globals()['clearButton%s' % self.var_num], self.teller, 3)
		self.signalMapper.setMapping(globals()['clearButton%s' % self.var_num],self.var_num)
		self.connect(globals()['clearButton%s' % self.var_num], SIGNAL("clicked()"), self.signalMapper, SLOT("map()"))
		globals()['timeSel%s' % self.var_num].show()
		globals()['ItemName%s' % self.var_num].setFocus(Qt.OtherFocusReason)
		self.myScrollArea.ensureWidgetVisible(globals()['timeSel%s' % self.var_num])
		self.teller +=1
		self.var_num +=1

class fileWindow(QWidget):
	def __init__(self,parent):
		super(fileWindow, self).__init__(parent)
		self.wg = QDialog(self)
		self.wg.resize(398, 692)
		sizePolicy = QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
		sizePolicy.setHorizontalStretch(0)
		sizePolicy.setVerticalStretch(0)
		sizePolicy.setHeightForWidth(self.wg.sizePolicy().hasHeightForWidth())
		self.wg.setSizePolicy(sizePolicy)

		if Language == "nl_NL":
			self.wg.setWindowTitle("WAV geluidsbestand kiezen")
		else:
			self.wg.setWindowTitle("Choose WAV soundfile")
		# folderbutton up
		folderButton_up = QPushButton(self.wg)
		folderButton_up.setIcon(QIcon.fromTheme("filemanager_folder_up"))
		folderButton_up.setMinimumSize(QSize(74,70))
		folderButton_up.setMaximumSize(QSize(74,70))
		# folder display
		self.folderButton = QMaemo5ValueButton(self.wg)
		self.folderButton.setIcon(QIcon.fromTheme("general_folder"))
		self.folderButton.setMinimumSize(QSize(0,70))
		# file list
		self.listWidget = QListWidget(self.wg)
		sizePolicy = QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
		sizePolicy.setHeightForWidth(self.listWidget.sizePolicy().hasHeightForWidth())
		self.listWidget.setSizePolicy(sizePolicy)
		self.listWidget.setMinimumSize(QSize(200, 0))
		self.listWidget.setContextMenuPolicy(Qt.CustomContextMenu)
		self.listWidget.setVerticalScrollBarPolicy(Qt.ScrollBarAsNeeded)
		self.listWidget.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
		# add to grid
		self.grid = QGridLayout(self.wg)
		self.grid.addWidget(folderButton_up,0,0,1,1)
		self.grid.addWidget(self.folderButton,0,1,1,1)
		self.grid.addWidget(self.listWidget, 2, 0, 1, 2)
		# actions
		self.connect(QApplication.desktop(), SIGNAL("resized(int)"), self.orientationChanged)
		self.connect(folderButton_up, SIGNAL("clicked()"),self.on_folderButton_up_clicked)
		self.connect(self.listWidget, SIGNAL("itemClicked(QListWidgetItem *)"), self.on_listWidget_itemClicked)

		# set initial path
		path = os.path.dirname(Alarmfile)
		if not os.path.isdir(path):
			path = "/home/user/MyDocs/"
		fileInfo = QFileInfo(path)
		self.folderButton.setText( fileInfo.fileName() )
		if path == "/":
			self.folderButton.setText( "/" )
			self.folderButton.setValueText( "" )
		self.FillBrowser(path)
		self.wg.show()

	def orientationChanged(self):
		screenGeometry = QApplication.desktop().screenGeometry()
		if screenGeometry.width() < screenGeometry.height():
			# portrait
			self.wg.resize(398, 692)

	def FillBrowser (self,Directory):
		global hPath
		hPath = Directory
		self.folderButton.setText( QFileInfo(Directory).fileName() )
		self.folderButton.setValueText(Directory)
		if Directory == "/":
			self.folderButton.setText("/")
			self.folderButton.setValueText("")
		self.listWidget.clear()

		# sort dirs/files case-insensitive
		dirs = sorted([d for d in os.listdir(Directory) if os.path.isdir(Directory + os.path.sep + d)])
		dirs.sort(key=lambda y: y.lower())
		filelist = sorted([f for f in os.listdir(Directory) if os.path.isfile(Directory + os.path.sep + f)])
		filelist.sort(key=lambda y: y.lower())
		dirs.extend(filelist)

		# add revelant ones to the list
		teller = 0
		for fileName in dirs:
			teller += 1
			f=os.path.join(Directory, fileName)
			if fileName == "." or fileName == "..":
				continue
			elif os.path.isdir(f):
				item1 = QListWidgetItem( self.listWidget )
				item1.setText(fileName)
				if fileName == ".videos":
					item1.setIcon(QIcon.fromTheme("filemanager_video_folder"))
				elif fileName == ".sounds":
					item1.setIcon(QIcon.fromTheme("filemanager_audio_folder"))
				elif fileName == "DCIM":
					item1.setIcon(QIcon.fromTheme("filemanager_camera_folder"))
				elif fileName == ".documents":
					item1.setIcon(QIcon.fromTheme("filemanager_document_folder"))
				elif fileName == ".images":
					item1.setIcon(QIcon.fromTheme("filemanager_image_folder"))
				else:
					item1.setIcon(QIcon.fromTheme("general_folder"))

				self.listWidget.insertItem( teller, item1 )
			elif os.path.isfile(f):
				if fileName.lower().endswith(('.wav')):
					item1 = QListWidgetItem( self.listWidget )
					item1.setText(fileName)
					item1.setIcon(QIcon.fromTheme("general_audio_file"))
					self.listWidget.insertItem( teller, item1 )

		if self.listWidget.count() > 0:
			self.listWidget.scrollToItem(self.listWidget.item(0))

	def on_folderButton_up_clicked(self):
		if  hPath == "/":
			return
		nPath = os.path.dirname(os.path.dirname(hPath+'/'))
		if nPath == "":
			nPath = "/"
		self.FillBrowser( nPath )
	
	def on_listWidget_itemClicked(self,item):
		global Alarmfile
		temp = hPath
		if temp != "/":
			temp = temp + "/"
		temp =temp + item.text()

		if os.path.isfile(temp):
			# save the newly chosen alarmfile preference
			Alarmfile = temp
			OptionChar = " "
			self.cooktimer_opts = parse_config(self,Cooktimer_CfgFile)
			self.cooktimer_opts["alarmfile"] = Alarmfile
			try:
				newConfigFile = open(Cooktimer_CfgFile,"w")
				for option in self.cooktimer_opts:
					newConfigFile.write(option + " " + self.cooktimer_opts[option] + "\n")
				newConfigFile.close()
				os.system('run-standalone.sh dbus-send --type=method_call --dest=org.freedesktop.Notifications  \
					/org/freedesktop/Notifications org.freedesktop.Notifications.SystemNoteInfoprint \
					string:"Configuration is successfully saved"')
			except:
				os.system('run-standalone.sh dbus-send --type=method_call --dest=org.freedesktop.Notifications  \
					/org/freedesktop/Notifications org.freedesktop.Notifications.SystemNoteInfoprint \
					string:"Could NOT save Configuration!"')
			self.wg.close()
		elif os.path.isdir(temp):
				self.FillBrowser(temp)


class FormWidget(QWidget):
	def __init__(self, parent):
		super(FormWidget, self).__init__(parent)
		grid = QGridLayout()
		global hoursPicked1
		global minutesPicked1
		global secondsPicked1
		global hoursPicked2
		global minutesPicked2
		global secondsPicked2
		global hoursPicked3
		global minutesPicked3
		global secondsPicked3
		global msgTxtPicked1_1, msgTimePicked1_1, msgTxtPicked1_2, msgTimePicked1_2, msgTxtPicked1_3, msgTimePicked1_3
		global msgTxtPicked2_1, msgTimePicked2_1, msgTxtPicked2_2, msgTimePicked2_2, msgTxtPicked2_3, msgTimePicked2_3
		global msgTxtPicked3_1, msgTimePicked3_1, msgTxtPicked3_2, msgTimePicked3_2, msgTxtPicked3_3, msgTimePicked3_3

		# Timer1
		self.Timer1 = QTimer()
		self.Timer1.timeout.connect(self.updateTimer1)
		# Timer2
		self.Timer2 = QTimer()
		self.Timer2.timeout.connect(self.updateTimer2)
		# Timer3
		self.Timer3 = QTimer()
		self.Timer3.timeout.connect(self.updateTimer3)
	 
		font = QFont()
		font.setPointSize(48)
		startTime= QTime(0, 0, 0)  

		if Language == "nl_NL":
			self.gerechtButton1 = QPushButton("Kies gerecht")
			self.gerechtButton2 = QPushButton("Kies gerecht")
			self.gerechtButton3 = QPushButton("Kies gerecht")
		else:
			self.gerechtButton1 = QPushButton("Choose dish")
			self.gerechtButton2 = QPushButton("Choose dish")
			self.gerechtButton3 = QPushButton("Choose dish")
		self.timeButton1 = QPushButton("00:00:00")
		self.timeButton2 = QPushButton("00:00:00")
		self.timeButton3 = QPushButton("00:00:00")
		# see if we need to set default dishes
		num_lines = sum(1 for line in open(Cooktimer_StartItems))
		file = codecs.open(Cooktimer_StartItems,"r", encoding="utf-8")
		data = file.readlines()
		file.close()
		if num_lines > 0:
			f = codecs.open(Cooktimer_ItemFile,"r", encoding="utf-8")
			lines = f.readlines()
			f.close()
			for count in range(0,num_lines):
				foundInItems = False;
				for count2 in range(0,len(lines)-1):
					if data[count].strip()+"|" in lines[count2]:
						foundInItems = True
						if count == 0:
							for count3 in range(lines[count2].count('|'),5):
								# add |, make sure all can be read
								lines[count2] = lines[count2].strip() + "|"
							(msgTxtPicked1_1, msgTimePicked1_1, msgTxtPicked1_2, msgTimePicked1_2, msgTxtPicked1_3, msgTimePicked1_3) = lines[count2].split('|')
							self.gerechtButton1.setText(msgTxtPicked1_1)
							self.timeButton1.setText(msgTimePicked1_1)
						if count == 1:
							for count3 in range(lines[count2].count('|'),5):
								# add |, make sure all can be read
								lines[count2] = lines[count2].strip() + "|"
							(msgTxtPicked2_1, msgTimePicked2_1, msgTxtPicked2_2, msgTimePicked2_2, msgTxtPicked2_3, msgTimePicked2_3) = lines[count2].split('|')
							self.gerechtButton2.setText(msgTxtPicked2_1)
							self.timeButton2.setText(msgTimePicked2_1)
						if count == 2:
							for count3 in range(lines[count2].count('|'),5):
								# add |, make sure all can be read
								lines[count2] = lines[count2].strip() + "|"
							(msgTxtPicked3_1, msgTimePicked3_1, msgTxtPicked3_2, msgTimePicked3_2, msgTxtPicked3_3, msgTimePicked3_3) = lines[count2].split('|')
							self.gerechtButton3.setText(msgTxtPicked3_1)
							self.timeButton3.setText(msgTimePicked3_1)
				if not foundInItems:
					# orphaned dish, remove it
					file = codecs.open(Cooktimer_StartItems,"w", encoding="utf-8")
					data[count] = ""
					data = "".join(data)
					file.write(data)
					file.close()
		# set styles of buttons
		self.gerechtButton1.setStyleSheet(
		"QPushButton {"
			"border: 1px solid #676B67;"
			"border-radius: 6px;"
			"background-color: #3A3B3A;"
			"background-color: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 0.67, "
				"stop: 0 #676967, stop: 1 #3A3B3A);"
		"}"
		"QPushButton:pressed {"
			"border: 1px solid #333333;"
			"background-color: #222222;"
			"background-color: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 0.67, "
				"stop: 0 #444444, stop: 1 #222222);"
		"}")
		self.timeButton2.setStyleSheet(
		"QPushButton {"
			"border: 1px solid #676B67;"
			"border-radius: 6px;"
			"background-color: #3A3B3A;"
			"background-color: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 0.67, "
				"stop: 0 #676967, stop: 1 #3A3B3A);"
		"}"
		"QPushButton:pressed {"
			"border: 1px solid #333333;"
			"background-color: #222222;"
			"background-color: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 0.67, "
				"stop: 0 #444444, stop: 1 #222222);"
		"}")
		self.gerechtButton2.setStyleSheet(
		"QPushButton {"
			"border: 1px solid #676B67;"
			"border-radius: 6px;"
			"background-color: #3A3B3A;"
			"background-color: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 0.67, "
				"stop: 0 #676967, stop: 1 #3A3B3A);"
		"}"
		"QPushButton:pressed {"
			"border: 1px solid #333333;"
			"background-color: #222222;"
			"background-color: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 0.67, "
				"stop: 0 #444444, stop: 1 #222222);"
		"}")

		self.timeButton3.setStyleSheet(
		"QPushButton {"
			"border: 1px solid #676B67;"
			"border-radius: 6px;"
			"background-color: #3A3B3A;"
			"background-color: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 0.67, "
				"stop: 0 #676967, stop: 1 #3A3B3A);"
		"}"
		"QPushButton:pressed {"
			"border: 1px solid #333333;"
			"background-color: #222222;"
			"background-color: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 0.67, "
				"stop: 0 #444444, stop: 1 #222222);"
		"}")
		self.gerechtButton3.setStyleSheet(
		"QPushButton {"
			"border: 1px solid #676B67;"
			"border-radius: 6px;"
			"background-color: #3A3B3A;"
			"background-color: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 0.67, "
				"stop: 0 #676967, stop: 1 #3A3B3A);"
		"}"
		"QPushButton:pressed {"
			"border: 1px solid #333333;"
			"background-color: #222222;"
			"background-color: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 0.67, "
				"stop: 0 #444444, stop: 1 #222222);"
		"}")

		self.initDishText = self.gerechtButton1.text()
		self.timeButton1.setStyleSheet(
		"QPushButton {"
			"border: 1px solid #676B67;"
			"border-radius: 6px;"
			"background-color: #3A3B3A;"
			"background-color: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 0.67, "
				"stop: 0 #676967, stop: 1 #3A3B3A);"
		"}"
		"QPushButton:pressed {"
			"border: 1px solid #333333;"
			"background-color: #222222;"
			"background-color: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 0.67, "
				"stop: 0 #444444, stop: 1 #222222);"
		"}")
		self.timeRemaining1 = QPushButton("00:00:00")
		self.timeRemaining1.setStyleSheet("QPushButton { background : #2A2B29; border-width: 1px; \
						   border-color: #202020 ; border-radius: 9px; border-style: inset; }")
		self.timeRemaining1.setFont(font)

		self.timeRemaining2 = QPushButton("00:00:00")
		self.timeRemaining2.setStyleSheet("QPushButton { background : #2A2B29; border-width: 1px; \
						   border-color: #202020 ; border-radius: 9px; border-style: inset; }")
		self.timeRemaining2.setFont(font)

		self.timeRemaining3 = QPushButton("00:00:00")
		self.timeRemaining3.setStyleSheet("QPushButton { background : #2A2B29; border-width: 1px; \
						   border-color: #202020 ; border-radius: 9px; border-style: inset; }")
		self.timeRemaining3.setFont(font)

		self.startButton1 = QPushButton('Start')
		self.startButton1.setStyleSheet(
		"QPushButton {"
			"border: 1px solid #676B67;"
			"border-radius: 6px;"
			"background-color: #3A3B3A;"
			"background-color: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 0.67, "
				"stop: 0 #676967, stop: 1 #3A3B3A);"
		"}"
		"QPushButton:pressed {"
			"border: 1px solid #333333;"
			"background-color: #222222;"
			"background-color: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 0.67, "
				"stop: 0 #444444, stop: 1 #222222);"
		"}")
		self.startButton2 = QPushButton('Start')
		self.startButton2.setStyleSheet(
		"QPushButton {"
			"border: 1px solid #676B67;"
			"border-radius: 6px;"
			"background-color: #3A3B3A;"
			"background-color: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 0.67, "
				"stop: 0 #676967, stop: 1 #3A3B3A);"
		"}"
		"QPushButton:pressed {"
			"border: 1px solid #333333;"
			"background-color: #222222;"
			"background-color: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 0.67, "
				"stop: 0 #444444, stop: 1 #222222);"
		"}")
		self.startButton3 = QPushButton('Start')
		self.startButton3.setStyleSheet(
		"QPushButton {"
			"border: 1px solid #676B67;"
			"border-radius: 6px;"
			"background-color: #3A3B3A;"
			"background-color: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 0.67, "
				"stop: 0 #676967, stop: 1 #3A3B3A);"
		"}"
		"QPushButton:pressed {"
			"border: 1px solid #333333;"
			"background-color: #222222;"
			"background-color: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 0.67, "
				"stop: 0 #444444, stop: 1 #222222);"
		"}")
		# correct size of buttons
		self.gerechtButton1.setMinimumHeight(65)
		self.gerechtButton1.setMaximumHeight(65)
		self.gerechtButton2.setMinimumHeight(65)
		self.gerechtButton2.setMaximumHeight(65)
		self.gerechtButton3.setMinimumHeight(65)
		self.gerechtButton3.setMaximumHeight(65)
		self.timeButton1.setMinimumHeight(65)
		self.timeButton1.setMaximumHeight(65)
		self.timeButton2.setMinimumHeight(65)
		self.timeButton2.setMaximumHeight(65)
		self.timeButton3.setMinimumHeight(65)
		self.timeButton3.setMaximumHeight(65)
		self.startButton1.setMinimumHeight(65)
		self.startButton1.setMaximumHeight(65)
		self.startButton2.setMinimumHeight(65)
		self.startButton2.setMaximumHeight(65)
		self.startButton3.setMinimumHeight(65)
		self.startButton3.setMaximumHeight(65)
		# add to grid
		grid.addWidget(self.gerechtButton1,0,0)
		grid.addWidget(self.timeButton1,0,1)
		grid.addWidget(self.startButton1,0,2)
		grid.addWidget(self.timeRemaining1,1,0,1,3)
		grid.addWidget(self.gerechtButton2,2,0)
		grid.addWidget(self.timeButton2,2,1)
		grid.addWidget(self.startButton2,2,2)
		grid.addWidget(self.timeRemaining2,3,0,1,3)
		grid.addWidget(self.gerechtButton3,4,0)
		grid.addWidget(self.timeButton3,4,1)
		grid.addWidget(self.startButton3,4,2)
		grid.addWidget(self.timeRemaining3,5,0,1,3)
		# Disable startbuttons by default
		if self.gerechtButton1.text() != "Kies gerecht" and self.gerechtButton1.text() != "Choose dish":
			self.startButton1.setEnabled(True)
			self.startButton1.setStyleSheet(
			"QPushButton {"
			"border: 1px solid #199909;"
			"border-radius: 6px;"
			"background-color: #116a06;"
			"background-color: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 0.67, "
			"stop: 0 #22c70d, stop: 1 #116a06);"
			"}"
			"QPushButton:pressed {"
			"border: 1px solid #333333;"
			"background-color: #222222;"
			"background-color: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 0.67, "
			"stop: 0 #444444, stop: 1 #222222);"
			"}")
			self.timeRemaining1.setStyleSheet("QPushButton { background : #2A2B29; border-width: 1px; \
							   border-color: #202020 ; border-radius: 9px; border-style: inset; }")
			self.timeRemaining1.setText(self.timeButton1.text())
			startTime1 = self.timeRemaining1.text()
			(hoursPicked1, minutesPicked1, secondsPicked1) = startTime1.split(':')
		else:
			self.startButton1.setEnabled(False)
		if self.gerechtButton2.text() != "Kies gerecht" and self.gerechtButton2.text() != "Choose dish":
			self.startButton2.setEnabled(True)
			self.startButton2.setStyleSheet(
			"QPushButton {"
			"border: 1px solid #199909;"
			"border-radius: 6px;"
			"background-color: #116a06;"
			"background-color: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 0.67, "
			"stop: 0 #22c70d, stop: 1 #116a06);"
			"}"
			"QPushButton:pressed {"
			"border: 1px solid #333333;"
			"background-color: #222222;"
			"background-color: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 0.67, "
			"stop: 0 #444444, stop: 1 #222222);"
			"}")
			self.timeRemaining2.setStyleSheet("QPushButton { background : #2A2B29; border-width: 1px; \
							   border-color: #202020 ; border-radius: 9px; border-style: inset; }")
			self.timeRemaining2.setText(self.timeButton2.text())
			startTime2 = self.timeRemaining2.text()
			(hoursPicked2, minutesPicked2, secondsPicked2) = startTime2.split(':')
		else:
			self.startButton2.setEnabled(False)
		if self.gerechtButton3.text() != "Kies gerecht" and self.gerechtButton3.text() != "Choose dish":
			self.startButton3.setEnabled(True)
			self.startButton3.setStyleSheet(
			"QPushButton {"
			"border: 1px solid #199909;"
			"border-radius: 6px;"
			"background-color: #116a06;"
			"background-color: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 0.67, "
			"stop: 0 #22c70d, stop: 1 #116a06);"
			"}"
			"QPushButton:pressed {"
			"border: 1px solid #333333;"
			"background-color: #222222;"
			"background-color: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 0.67, "
			"stop: 0 #444444, stop: 1 #222222);"
			"}")
			self.timeRemaining3.setStyleSheet("QPushButton { background : #2A2B29; border-width: 1px; \
							   border-color: #202020 ; border-radius: 9px; border-style: inset; }")
			self.timeRemaining3.setText(self.timeButton3.text())
			startTime3 = self.timeRemaining3.text()
			(hoursPicked3, minutesPicked3, secondsPicked3) = startTime3.split(':')
		else:
			self.startButton3.setEnabled(False)
		self.timeRemaining1.setEnabled(False)
		self.timeRemaining2.setEnabled(False)
		self.timeRemaining3.setEnabled(False)
		# set minimum column width for time and start button
		grid.setColumnMinimumWidth(1, 120)
		grid.setColumnMinimumWidth(2, 120)
		# Let's make something happen when the button is pushed!
		self.connect(self.startButton1, SIGNAL("clicked()"), self.startTimer1)
		self.connect(self.startButton2, SIGNAL("clicked()"), self.startTimer2)
		self.connect(self.startButton3, SIGNAL("clicked()"), self.startTimer3)
		self.connect(self.gerechtButton1, SIGNAL("clicked()"), self.setDefaultTime1)
		self.connect(self.gerechtButton2, SIGNAL("clicked()"), self.setDefaultTime2)
		self.connect(self.gerechtButton3, SIGNAL("clicked()"), self.setDefaultTime3)
		self.connect(self.timeButton1, SIGNAL("clicked()"), self.setPickedTime1)
		self.connect(self.timeButton2, SIGNAL("clicked()"), self.setPickedTime2)
		self.connect(self.timeButton3, SIGNAL("clicked()"), self.setPickedTime3)
		self.connect(self.timeRemaining1, SIGNAL("clicked()"), self.togglePause1)
		self.connect(self.timeRemaining2, SIGNAL("clicked()"), self.togglePause2)
		self.connect(self.timeRemaining3, SIGNAL("clicked()"), self.togglePause3)
	 
		# Set the layout on the window: this means that our button will actually be displayed.
		self.setLayout(grid)
 
	def startTimer1(self):
		global secondsPicked1
		global minutesPicked1
		global hoursPicked1
		global pause1
		startTime1 = str('%02d'  % int(hoursPicked1)) + ":" + str('%02d' % int(minutesPicked1)) + ":" + str('%02d' % int(secondsPicked1))
		if self.Timer1.isActive() or pause1:
			self.Timer1.stop()
			pause1 = False
			self.timeRemaining1.setEnabled(False)
			self.timeRemaining1.setText(self.timeButton1.text())
			self.startButton1.setText('Start')
			self.startButton1.setStyleSheet(
			"QPushButton {"
			"border: 1px solid #199909;"
			"border-radius: 6px;"
			"background-color: #116a06;"
			"background-color: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 0.67, "
			"stop: 0 #22c70d, stop: 1 #116a06);"
			"}"
			"QPushButton:pressed {"
			"border: 1px solid #333333;"
			"background-color: #222222;"
			"background-color: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 0.67, "
			"stop: 0 #444444, stop: 1 #222222);"
			"}")
			self.timeRemaining1.setStyleSheet("QPushButton { background : #2A2B29; border-width: 1px; \
							   border-color: #202020 ; border-radius: 9px; border-style: inset; }")
			if startTime1 ==  "00:00:00":
				self.startButton1.setEnabled(False)
				self.startButton1.setStyleSheet(
				"QPushButton {"
					"border: 1px solid #676B67;"
					"border-radius: 6px;"
					"background-color: #3A3B3A;"
					"background-color: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 0.67, "
						"stop: 0 #676967, stop: 1 #3A3B3A);"
				"}"
				"QPushButton:pressed {"
					"border: 1px solid #333333;"
					"background-color: #222222;"
					"background-color: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 0.67, "
						"stop: 0 #444444, stop: 1 #222222);"
				"}")
		else:
			if startTime1 != "00:00:00":
				self.Timer1.start(1000)
				self.timeRemaining1.setEnabled(True)
				(h, m, s) = startTime1.split(':')
				self.startSecs1 = int(h) * 3600 + int(m) * 60 + int(s)
				self.timeRemaining1.setStyleSheet("QPushButton { background : #21610B; color : white; border-width: 1px; \
								   border-color: #3E8F23 ; border-radius: 9px; border-style: outset; }")
				self.startButton1.setText('Stop')
				self.startButton1.setStyleSheet(
				"QPushButton {"
				"border: 1px solid #E81F11;"
				"border-radius: 6px;"
				"background-color: #95211B;"
				"background-color: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 0.67, "
				"stop: 0 #FF1410, stop: 1 #95211B);"
				"}"
				"QPushButton:pressed {"
				"border: 1px solid #333333;"
				"background-color: #222222;"
				"background-color: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 0.67, "
				"stop: 0 #444444, stop: 1 #222222);"
				"}")

	def startTimer2(self):
		global secondsPicked2
		global minutesPicked2
		global hoursPicked2
		global pause2
		startTime2 = str('%02d'  % int(hoursPicked2)) + ":" + str('%02d' % int(minutesPicked2)) + ":" + str('%02d' % int(secondsPicked2))
		if self.Timer2.isActive() or pause2:
			self.Timer2.stop()
			pause2 = False
			self.timeRemaining2.setEnabled(False)
			self.timeRemaining2.setText(self.timeButton2.text())
			self.startButton2.setText('Start')
			self.startButton2.setStyleSheet(
			"QPushButton {"
			"border: 1px solid #199909;"
			"border-radius: 6px;"
			"background-color: #116a06;"
			"background-color: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 0.67, "
			"stop: 0 #22c70d, stop: 1 #116a06);"
			"}"
			"QPushButton:pressed {"
			"border: 1px solid #333333;"
			"background-color: #222222;"
			"background-color: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 0.67, "
			"stop: 0 #444444, stop: 1 #222222);"
			"}")
			self.timeRemaining2.setStyleSheet("QPushButton { background : #2A2B29; border-width: 1px; \
							   border-color: #202020 ; border-radius: 9px; border-style: inset; }")
			if startTime2 ==  "00:00:00":
				self.startButton2.setEnabled(False)
				self.startButton2.setStyleSheet(
				"QPushButton {"
					"border: 1px solid #676B67;"
					"border-radius: 6px;"
					"background-color: #3A3B3A;"
					"background-color: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 0.67, "
						"stop: 0 #676967, stop: 1 #3A3B3A);"
				"}"
				"QPushButton:pressed {"
					"border: 1px solid #333333;"
					"background-color: #222222;"
					"background-color: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 0.67, "
						"stop: 0 #444444, stop: 1 #222222);"
				"}")
		else:
			if startTime2 != "00:00:00":
				self.Timer2.start(1000)
				self.timeRemaining2.setEnabled(True)
				(h, m, s) = startTime2.split(':')
				self.startSecs2 = int(h) * 3600 + int(m) * 60 + int(s)
				self.timeRemaining2.setStyleSheet("QPushButton { background : #21610B; color : white; border-width: 1px; \
								   border-color: #3E8F23 ; border-radius: 9px; border-style: outset; }")
				self.startButton2.setText('Stop')
				self.startButton2.setStyleSheet(
				"QPushButton {"
				"border: 1px solid #E81F11;"
				"border-radius: 6px;"
				"background-color: #95211B;"
				"background-color: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 0.67, "
				"stop: 0 #FF1410, stop: 1 #95211B);"
				"}"
				"QPushButton:pressed {"
				"border: 1px solid #333333;"
				"background-color: #222222;"
				"background-color: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 0.67, "
				"stop: 0 #444444, stop: 1 #222222);"
				"}")

	def startTimer3(self):
		global secondsPicked3
		global minutesPicked3
		global hoursPicked3
		global pause3
		startTime3 = str('%02d'  % int(hoursPicked3)) + ":" + str('%02d' % int(minutesPicked3)) + ":" + str('%02d' % int(secondsPicked3))
		if self.Timer3.isActive() or pause3:
			self.Timer3.stop()
			pause3 = False
			self.timeRemaining3.setEnabled(False)
			self.timeRemaining3.setText(self.timeButton3.text())
			self.startButton3.setText('Start')
			self.startButton3.setStyleSheet(
			"QPushButton {"
			"border: 1px solid #199909;"
			"border-radius: 6px;"
			"background-color: #116a06;"
			"background-color: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 0.67, "
			"stop: 0 #22c70d, stop: 1 #116a06);"
			"}"
			"QPushButton:pressed {"
			"border: 1px solid #333333;"
			"background-color: #222222;"
			"background-color: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 0.67, "
			"stop: 0 #444444, stop: 1 #222222);"
			"}")
			self.timeRemaining3.setStyleSheet("QPushButton { background : #2A2B29; border-width: 1px; \
							   border-color: #202020 ; border-radius: 9px; border-style: inset; }")
			if startTime3 ==  "00:00:00":
				self.startButton3.setEnabled(False)
				self.startButton3.setStyleSheet(
				"QPushButton {"
					"border: 1px solid #676B67;"
					"border-radius: 6px;"
					"background-color: #3A3B3A;"
					"background-color: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 0.67, "
						"stop: 0 #676967, stop: 1 #3A3B3A);"
				"}"
				"QPushButton:pressed {"
					"border: 1px solid #333333;"
					"background-color: #222222;"
					"background-color: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 0.67, "
						"stop: 0 #444444, stop: 1 #222222);"
				"}")
		else:
			if startTime3 != "00:00:00":
				self.Timer3.start(1000)
				self.timeRemaining3.setEnabled(True)
				(h, m, s) = startTime3.split(':')
				self.startSecs3 = int(h) * 3600 + int(m) * 60 + int(s)
				self.timeRemaining3.setStyleSheet("QPushButton { background : #21610B; color : white; border-width: 1px; \
								   border-color: #3E8F23 ; border-radius: 9px; border-style: outset; }")
				self.startButton3.setText('Stop')
				self.startButton3.setStyleSheet(
				"QPushButton {"
				"border: 1px solid #E81F11;"
				"border-radius: 6px;"
				"background-color: #95211B;"
				"background-color: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 0.67, "
				"stop: 0 #FF1410, stop: 1 #95211B);"
				"}"
				"QPushButton:pressed {"
				"border: 1px solid #333333;"
				"background-color: #222222;"
				"background-color: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 0.67, "
				"stop: 0 #444444, stop: 1 #222222);"
				"}")

	def updateTimer1(self):
		global dishName1banner
		self.startSecs1 -=1
		hhmmss_format=format_seconds_to_hhmmss(self.startSecs1)
		self.timeRemaining1.setText(hhmmss_format)
		# act on sub actions
		if msgTimePicked1_1 == hhmmss_format:
			Alarm(self)
			bus = dbus.SessionBus()
			proxy = bus.get_object('org.freedesktop.Notifications', '/org/freedesktop/Notifications')
			interface = dbus.Interface(proxy,dbus_interface='org.freedesktop.Notifications')
			interface.Notify('Notification', 0, 'control_bluetooth_paired', "[timer 1] " + dishName1banner, msgTxtPicked1_1, [], {}, 0)
		if msgTimePicked1_2 == hhmmss_format:
			Alarm(self)
			bus = dbus.SessionBus()
			proxy = bus.get_object('org.freedesktop.Notifications', '/org/freedesktop/Notifications')
			interface = dbus.Interface(proxy,dbus_interface='org.freedesktop.Notifications')
			interface.Notify('Notification', 0, 'control_bluetooth_paired', "[timer 1] " + dishName1banner, msgTxtPicked1_2, [], {}, 0)
		if msgTimePicked1_3 == hhmmss_format:
			Alarm(self)
			bus = dbus.SessionBus()
			proxy = bus.get_object('org.freedesktop.Notifications', '/org/freedesktop/Notifications')
			interface = dbus.Interface(proxy,dbus_interface='org.freedesktop.Notifications')
			interface.Notify('Notification', 0, 'control_bluetooth_paired', "[timer 1] " + dishName1banner, msgTxtPicked1_3, [], {}, 0)

		if self.startSecs1 == 0:
			self.Timer1.stop()
			self.timeRemaining1.setStyleSheet("QPushButton { background : #8A0808; color : white; border-width: 1px; \
							   border-color: #AB0E0E ; border-radius: 9px; border-style: outset; }")

			if not pause2:
				if self.Timer2.isActive():
					self.timeRemaining2.setStyleSheet("QPushButton { background : #21610B; color : white; border-width: 1px; \
									   border-color: #3E8F23 ; border-radius: 9px; border-style: outset; }")
				else:
					self.timeRemaining2.setStyleSheet("QPushButton { background : #2A2B29; border-width: 1px; \
									   border-color: #202020 ; border-radius: 9px; border-style: inset; }")
					self.timeRemaining2.setEnabled(False)
			if not pause3:
				if self.Timer3.isActive():
					self.timeRemaining2.setStyleSheet("QPushButton { background : #21610B; color : white; border-width: 1px; \
									   border-color: #3E8F23 ; border-radius: 9px; border-style: outset; }")
				else:
					self.timeRemaining3.setStyleSheet("QPushButton { background : #2A2B29; border-width: 1px; \
									   border-color: #202020 ; border-radius: 9px; border-style: inset; }")
					self.timeRemaining3.setEnabled(False)
			if dishName1banner == "":
				dishName1banner = "Timer 1"
			if Alarmbanner:
				if Language == "nl_NL":
					printMsg(self,"<h2>" + dishName1banner + "</h2><h4>timer 1 klaar!</h4>",10000)
				else:
					printMsg(self,"<h2>" + dishName1banner + "</h2><h4>timer 1 ready!</h4>",10000)
			Alarm(self)
			self.startButton1.setText('Start')
			self.startButton1.setStyleSheet(
			"QPushButton {"
			"border: 1px solid #199909;"
			"border-radius: 6px;"
			"background-color: #116a06;"
			"background-color: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 0.67, "
			"stop: 0 #22c70d, stop: 1 #116a06);"
			"}"
			"QPushButton:pressed {"
			"border: 1px solid #333333;"
			"background-color: #222222;"
			"background-color: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 0.67, "
			"stop: 0 #444444, stop: 1 #222222);"
			"}")

	def updateTimer2(self):
		global dishName2banner
		self.startSecs2 -=1
		hhmmss_format=format_seconds_to_hhmmss(self.startSecs2)
		self.timeRemaining2.setText(hhmmss_format)
		# act on sub actions
		if msgTimePicked2_1 == hhmmss_format:
			Alarm(self)
			bus = dbus.SessionBus()
			proxy = bus.get_object('org.freedesktop.Notifications', '/org/freedesktop/Notifications')
			interface = dbus.Interface(proxy,dbus_interface='org.freedesktop.Notifications')
			interface.Notify('Notification', 0, 'control_bluetooth_paired', "[timer 2] " + dishName2banner, msgTxtPicked2_1, [], {}, 0)
		if msgTimePicked2_2 == hhmmss_format:
			Alarm(self)
			bus = dbus.SessionBus()
			proxy = bus.get_object('org.freedesktop.Notifications', '/org/freedesktop/Notifications')
			interface = dbus.Interface(proxy,dbus_interface='org.freedesktop.Notifications')
			interface.Notify('Notification', 0, 'control_bluetooth_paired', "[timer 2] " + dishName2banner, msgTxtPicked2_2, [], {}, 0)
		if msgTimePicked2_3 == hhmmss_format:
			Alarm(self)
			bus = dbus.SessionBus()
			proxy = bus.get_object('org.freedesktop.Notifications', '/org/freedesktop/Notifications')
			interface = dbus.Interface(proxy,dbus_interface='org.freedesktop.Notifications')
			interface.Notify('Notification', 0, 'control_bluetooth_paired', "[timer 2] " + dishName2banner, msgTxtPicked2_3, [], {}, 0)
		if self.startSecs2 == 0:
			self.Timer2.stop()
			self.timeRemaining2.setStyleSheet("QPushButton { background : #8A0808; color : white; border-width: 1px; \
							   border-color: #AB0E0E ; border-radius: 9px; border-style: outset; }")
			# set other alarm backgrounds to default
			if not pause1:
				if self.Timer1.isActive():
					self.timeRemaining1.setStyleSheet("QPushButton { background : #21610B; color : white; border-width: 1px; \
									   border-color: #3E8F23 ; border-radius: 9px; border-style: outset; }")
				else:
					self.timeRemaining1.setStyleSheet("QPushButton { background : #2A2B29; border-width: 1px; \
									   border-color: #202020 ; border-radius: 9px; border-style: inset; }")
					self.timeRemaining1.setEnabled(False)
			if not pause3:
				if self.Timer3.isActive():
					self.timeRemaining3.setStyleSheet("QPushButton { background : #21610B; color : white; border-width: 1px; \
									   border-color: #3E8F23 ; border-radius: 9px; border-style: outset; }")
				else:
					self.timeRemaining3.setStyleSheet("QPushButton { background : #2A2B29; border-width: 1px; \
									   border-color: #202020 ; border-radius: 9px; border-style: inset; }")
					self.timeRemaining3.setEnabled(False)
			if dishName2banner == "":
				dishName2banner = "Timer 2"
			if Alarmbanner:
				if Language == "nl_NL":
					printMsg(self,"<h2>" + dishName2banner + "</h2><h4>timer 2 klaar!</h4>",10000)
				else:
					printMsg(self,"<h2>" + dishName2banner + "</h2><h4>timer 2 ready!</h4>",10000)
			Alarm(self)
			self.startButton2.setText('Start')
			self.startButton2.setStyleSheet(
			"QPushButton {"
			"border: 1px solid #199909;"
			"border-radius: 6px;"
			"background-color: #116a06;"
			"background-color: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 0.67, "
			"stop: 0 #22c70d, stop: 1 #116a06);"
			"}"
			"QPushButton:pressed {"
			"border: 1px solid #333333;"
			"background-color: #222222;"
			"background-color: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 0.67, "
			"stop: 0 #444444, stop: 1 #222222);"
			"}")

	def updateTimer3(self):
		global dishName3banner
		self.startSecs3 -=1
		hhmmss_format=format_seconds_to_hhmmss(self.startSecs3)
		self.timeRemaining3.setText(hhmmss_format)
		# act on sub actions
		if msgTimePicked3_1 == hhmmss_format:
			Alarm(self)
			bus = dbus.SessionBus()
			proxy = bus.get_object('org.freedesktop.Notifications', '/org/freedesktop/Notifications')
			interface = dbus.Interface(proxy,dbus_interface='org.freedesktop.Notifications')
			interface.Notify('Notification', 0, 'control_bluetooth_paired', "[timer 3] " + dishName3banner, msgTxtPicked3_1, [], {}, 0)
		if msgTimePicked3_2 == hhmmss_format:
			Alarm(self)
			bus = dbus.SessionBus()
			proxy = bus.get_object('org.freedesktop.Notifications', '/org/freedesktop/Notifications')
			interface = dbus.Interface(proxy,dbus_interface='org.freedesktop.Notifications')
			interface.Notify('Notification', 0, 'control_bluetooth_paired', "[timer 3] " + dishName3banner, msgTxtPicked3_2, [], {}, 0)
		if msgTimePicked3_3 == hhmmss_format:
			Alarm(self)
			bus = dbus.SessionBus()
			proxy = bus.get_object('org.freedesktop.Notifications', '/org/freedesktop/Notifications')
			interface = dbus.Interface(proxy,dbus_interface='org.freedesktop.Notifications')
			interface.Notify('Notification', 0, 'control_bluetooth_paired', "[timer 3] " + dishName3banner, msgTxtPicked3_3, [], {}, 0)
		if self.startSecs3 == 0:
			self.Timer3.stop()
			self.timeRemaining3.setStyleSheet("QPushButton { background : #8A0808; color : white; border-width: 1px; \
							   border-color: #AB0E0E ; border-radius: 9px; border-style: outset; }")
			# set other alarm backgrounds to default
			if not pause1:
				if self.Timer1.isActive():
					self.timeRemaining1.setStyleSheet("QPushButton { background : #21610B; color : white; border-width: 1px; \
									   border-color: #3E8F23 ; border-radius: 9px; border-style: outset; }")
				else:
					self.timeRemaining1.setStyleSheet("QPushButton { background : #2A2B29; border-width: 1px; \
									   border-color: #202020 ; border-radius: 9px; border-style: inset; }")
					self.timeRemaining1.setEnabled(False)
			if not pause2:
				if self.Timer2.isActive():
					self.timeRemaining2.setStyleSheet("QPushButton { background : #21610B; color : white; border-width: 1px; \
									   border-color: #3E8F23 ; border-radius: 9px; border-style: outset; }")
				else:
					self.timeRemaining2.setStyleSheet("QPushButton { background : #2A2B29; border-width: 1px; \
									   border-color: #202020 ; border-radius: 9px; border-style: inset; }")
					self.timeRemaining2.setEnabled(False)
			if dishName3banner == "":
				dishName3banner = "Timer 3"
			if Alarmbanner:
				if Language == "nl_NL":
					printMsg(self,"<h2>" + dishName3banner + "</h2><h4>timer 3 klaar!</h4>",10000)
				else:
					printMsg(self,"<h2>" + dishName3banner + "</h2><h4>timer 3 ready!</h4>",10000)
			Alarm(self)
			self.startButton3.setText('Start')
			self.startButton3.setStyleSheet(
			"QPushButton {"
			"border: 1px solid #199909;"
			"border-radius: 6px;"
			"background-color: #116a06;"
			"background-color: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 0.67, "
			"stop: 0 #22c70d, stop: 1 #116a06);"
			"}"
			"QPushButton:pressed {"
			"border: 1px solid #333333;"
			"background-color: #222222;"
			"background-color: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 0.67, "
			"stop: 0 #444444, stop: 1 #222222);"
			"}")

	def setDefaultTime1(self):
		global secondsPicked1
		global minutesPicked1
		global hoursPicked1
		global dishName1
		global dishName1banner
		global currSelector
		global msgTxtPicked1_1
		global msgTimePicked1_1
		global msgTxtPicked1_2
		global msgTimePicked1_2
		global msgTxtPicked1_3
		global msgTimePicked1_3

		currSelector = 1
		dishPick = DishPickDialog(self)
		dishPick.show()
		if dishName1:
			self.gerechtButton1.setText(dishName1)
			dish_items = load_dishes(self)
			(hoursPicked1, minutesPicked1, secondsPicked1) = dish_items[dishPicked1Nbr][1][:8].split(':')
			hours = '%02d' % int(hoursPicked1)
			minutes = '%02d' % int(minutesPicked1)
			seconds = '%02d' % int(secondsPicked1)
			timestring = hours + ":" + minutes + ":" + seconds
			self.timeButton1.setText(timestring)

			xtrInfo = dish_items[dishPicked1Nbr][1]
			# | = 0: no extra info 6: all extra messages used
			for count in range(xtrInfo.count('|'),6):
				# add |, make sure all can be read
				xtrInfo = xtrInfo + "|"
			(dummy, msgTxtPicked1_1, msgTimePicked1_1, msgTxtPicked1_2, msgTimePicked1_2, msgTxtPicked1_3, msgTimePicked1_3) = xtrInfo.split('|')

			if not self.Timer1.isActive() and not pause1:
				self.timeRemaining1.setText(timestring)
				if timestring == "00:00:00":
					self.startButton1.setEnabled(False)
					self.startButton1.setStyleSheet(
					"QPushButton {"
						"border: 1px solid #676B67;"
						"border-radius: 6px;"
						"background-color: #3A3B3A;"
						"background-color: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 0.67, "
							"stop: 0 #676967, stop: 1 #3A3B3A);"
					"}"
					"QPushButton:pressed {"
						"border: 1px solid #333333;"
						"background-color: #222222;"
						"background-color: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 0.67, "
							"stop: 0 #444444, stop: 1 #222222);"
					"}")
				else:
					self.startButton1.setEnabled(True)
					self.startButton1.setStyleSheet(
					"QPushButton {"
					"border: 1px solid #199909;"
					"border-radius: 6px;"
					"background-color: #116a06;"
					"background-color: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 0.67, "
					"stop: 0 #22c70d, stop: 1 #116a06);"
					"}"
					"QPushButton:pressed {"
					"border: 1px solid #333333;"
					"background-color: #222222;"
					"background-color: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 0.67, "
					"stop: 0 #444444, stop: 1 #222222);"
					"}")
		# clear it again
		dishName1banner = dishName1
		dishName1 = ""

	def setDefaultTime2(self):
		global secondsPicked2
		global minutesPicked2
		global hoursPicked2
		global dishName2
		global dishName2banner
		global currSelector
		global msgTxtPicked2_1
		global msgTimePicked2_1
		global msgTxtPicked2_2
		global msgTimePicked2_2
		global msgTxtPicked2_3
		global msgTimePicked2_3

		currSelector = 2
		dishPick = DishPickDialog(self)
		dishPick.show()
		if dishName2:
			self.gerechtButton2.setText(dishName2)
			dish_items = load_dishes(self)
			(hoursPicked2, minutesPicked2, secondsPicked2) = dish_items[dishPicked2Nbr][1][:8].split(':')
			hours = '%02d' % int(hoursPicked2)
			minutes = '%02d' % int(minutesPicked2)
			seconds = '%02d' % int(secondsPicked2)
			timestring = hours + ":" + minutes + ":" + seconds
			self.timeButton2.setText(timestring)

			xtrInfo = dish_items[dishPicked2Nbr][1]
			# | = 0: no extra info 6: all extra messages used
			for count in range(xtrInfo.count('|'),6):
				# add |, make sure all can be read
				xtrInfo = xtrInfo + "|"
			(dummy, msgTxtPicked2_1, msgTimePicked2_1, msgTxtPicked2_2, msgTimePicked2_2, msgTxtPicked2_3, msgTimePicked2_3) = xtrInfo.split('|')

			if not self.Timer2.isActive() and not pause2:
				self.timeRemaining2.setText(timestring)
				if timestring == "00:00:00":
					self.startButton2.setEnabled(False)
					self.startButton2.setStyleSheet(
					"QPushButton {"
						"border: 1px solid #676B67;"
						"border-radius: 6px;"
						"background-color: #3A3B3A;"
						"background-color: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 0.67, "
							"stop: 0 #676967, stop: 1 #3A3B3A);"
					"}"
					"QPushButton:pressed {"
						"border: 1px solid #333333;"
						"background-color: #222222;"
						"background-color: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 0.67, "
							"stop: 0 #444444, stop: 1 #222222);"
					"}")
				else:
					self.startButton2.setEnabled(True)
					self.startButton2.setStyleSheet(
					"QPushButton {"
					"border: 1px solid #199909;"
					"border-radius: 6px;"
					"background-color: #116a06;"
					"background-color: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 0.67, "
					"stop: 0 #22c70d, stop: 1 #116a06);"
					"}"
					"QPushButton:pressed {"
					"border: 1px solid #333333;"
					"background-color: #222222;"
					"background-color: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 0.67, "
					"stop: 0 #444444, stop: 1 #222222);"
					"}")
		# clear it again
		dishName2banner = dishName2
		dishName2 = ""

	def setDefaultTime3(self):
		global secondsPicked3
		global minutesPicked3
		global hoursPicked3
		global dishName3
		global dishName3banner
		global currSelector
		global msgTxtPicked3_1
		global msgTimePicked3_1
		global msgTxtPicked3_2
		global msgTimePicked3_2
		global msgTxtPicked3_3
		global msgTimePicked3_3

		currSelector = 3
		dishPick = DishPickDialog(self)
		dishPick.show()
		if dishName3:
			self.gerechtButton3.setText(dishName3)
			dish_items = load_dishes(self)
			(hoursPicked3, minutesPicked3, secondsPicked3) = dish_items[dishPicked3Nbr][1][:8].split(':')
			hours = '%02d' % int(hoursPicked3)
			minutes = '%02d' % int(minutesPicked3)
			seconds = '%02d' % int(secondsPicked3)
			timestring = hours + ":" + minutes + ":" + seconds
			self.timeButton3.setText(timestring)

			xtrInfo = dish_items[dishPicked3Nbr][1]
			# | = 0: no extra info 6: all extra messages used
			for count in range(xtrInfo.count('|'),6):
				# add |, make sure all can be read
				xtrInfo = xtrInfo + "|"
			(dummy, msgTxtPicked3_1, msgTimePicked3_1, msgTxtPicked3_2, msgTimePicked3_2, msgTxtPicked3_3, msgTimePicked3_3) = xtrInfo.split('|')

			if not self.Timer3.isActive() and not pause3:
				self.timeRemaining3.setText(timestring)
				if timestring == "00:00:00":
					self.startButton3.setEnabled(False)
					self.startButton3.setStyleSheet(
					"QPushButton {"
						"border: 1px solid #676B67;"
						"border-radius: 6px;"
						"background-color: #3A3B3A;"
						"background-color: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 0.67, "
							"stop: 0 #676967, stop: 1 #3A3B3A);"
					"}"
					"QPushButton:pressed {"
						"border: 1px solid #333333;"
						"background-color: #222222;"
						"background-color: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 0.67, "
							"stop: 0 #444444, stop: 1 #222222);"
					"}")
				else:
					self.startButton3.setEnabled(True)
					self.startButton3.setStyleSheet(
					"QPushButton {"
					"border: 1px solid #199909;"
					"border-radius: 6px;"
					"background-color: #116a06;"
					"background-color: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 0.67, "
					"stop: 0 #22c70d, stop: 1 #116a06);"
					"}"
					"QPushButton:pressed {"
					"border: 1px solid #333333;"
					"background-color: #222222;"
					"background-color: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 0.67, "
					"stop: 0 #444444, stop: 1 #222222);"
					"}")
		# clear it again
		dishName3banner = dishName3
		dishName3 = ""

	def setPickedTime1(self):
		global secondsPicked1
		global minutesPicked1
		global hoursPicked1
		global currSelector
		global pause1
		global dishName1banner
		currSelector = 1
		timePick = TimePickDialog(self)
		timePick.show()  
		hours = '%02d' % int(hoursPicked1)
		minutes = '%02d' % int(minutesPicked1)
		seconds = '%02d' % int(secondsPicked1)
		timestring = hours + ":" + minutes + ":" + seconds
		self.timeButton1.setText(timestring)
		if timestring == "00:00:00":
			self.gerechtButton1.setText(self.initDishText)
			dishName1banner = ""
		if not self.Timer1.isActive() and not pause1:
			self.timeRemaining1.setText(timestring)
			if timestring == "00:00:00":
				self.startButton1.setEnabled(False)
				self.startButton1.setStyleSheet(
				"QPushButton {"
					"border: 1px solid #676B67;"
					"border-radius: 6px;"
					"background-color: #3A3B3A;"
					"background-color: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 0.67, "
						"stop: 0 #676967, stop: 1 #3A3B3A);"
				"}"
				"QPushButton:pressed {"
					"border: 1px solid #333333;"
					"background-color: #222222;"
					"background-color: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 0.67, "
						"stop: 0 #444444, stop: 1 #222222);"
				"}")
			else:
				self.startButton1.setEnabled(True)
				self.startButton1.setStyleSheet(
				"QPushButton {"
				"border: 1px solid #199909;"
				"border-radius: 6px;"
				"background-color: #116a06;"
				"background-color: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 0.67, "
				"stop: 0 #22c70d, stop: 1 #116a06);"
				"}"
				"QPushButton:pressed {"
				"border: 1px solid #333333;"
				"background-color: #222222;"
				"background-color: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 0.67, "
				"stop: 0 #444444, stop: 1 #222222);"
				"}")

	def setPickedTime2(self):
		global secondsPicked2
		global minutesPicked2
		global hoursPicked2
		global currSelector
		global pause2
		global dishName2banner
		currSelector = 2
		timePick = TimePickDialog(self)
		timePick.show()  
		hours = '%02d' % int(hoursPicked2)
		minutes = '%02d' % int(minutesPicked2)
		seconds = '%02d' % int(secondsPicked2)
		timestring = hours + ":" + minutes + ":" + seconds
		self.timeButton2.setText(timestring)
		if timestring == "00:00:00":
			self.gerechtButton2.setText(self.initDishText)
			dishName2banner = ""
		if not self.Timer2.isActive() and not pause2:
			self.timeRemaining2.setText(timestring)
			if timestring == "00:00:00":
				self.startButton2.setEnabled(False)
				self.startButton2.setStyleSheet(
				"QPushButton {"
					"border: 1px solid #676B67;"
					"border-radius: 6px;"
					"background-color: #3A3B3A;"
					"background-color: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 0.67, "
						"stop: 0 #676967, stop: 1 #3A3B3A);"
				"}"
				"QPushButton:pressed {"
					"border: 1px solid #333333;"
					"background-color: #222222;"
					"background-color: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 0.67, "
						"stop: 0 #444444, stop: 1 #222222);"
				"}")
			else:
				self.startButton2.setEnabled(True)
				self.startButton2.setStyleSheet(
				"QPushButton {"
				"border: 1px solid #199909;"
				"border-radius: 6px;"
				"background-color: #116a06;"
				"background-color: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 0.67, "
				"stop: 0 #22c70d, stop: 1 #116a06);"
				"}"
				"QPushButton:pressed {"
				"border: 1px solid #333333;"
				"background-color: #222222;"
				"background-color: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 0.67, "
				"stop: 0 #444444, stop: 1 #222222);"
				"}")

	def setPickedTime3(self):
		global secondsPicked3
		global minutesPicked3
		global hoursPicked3
		global currSelector
		global pause3
		global dishName3banner
		currSelector = 3
		timePick = TimePickDialog(self)
		timePick.show()  
		hours = '%02d' % int(hoursPicked3)
		minutes = '%02d' % int(minutesPicked3)
		seconds = '%02d' % int(secondsPicked3)
		timestring = hours + ":" + minutes + ":" + seconds
		self.timeButton3.setText(timestring)
		if timestring == "00:00:00":
			self.gerechtButton3.setText(self.initDishText)
			dishName3banner = ""
		if not self.Timer3.isActive() and not pause3:
			self.timeRemaining3.setText(timestring)
			if timestring == "00:00:00":
				self.startButton3.setEnabled(False)
				self.startButton3.setStyleSheet(
				"QPushButton {"
					"border: 1px solid #676B67;"
					"border-radius: 6px;"
					"background-color: #3A3B3A;"
					"background-color: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 0.67, "
						"stop: 0 #676967, stop: 1 #3A3B3A);"
				"}"
				"QPushButton:pressed {"
					"border: 1px solid #333333;"
					"background-color: #222222;"
					"background-color: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 0.67, "
						"stop: 0 #444444, stop: 1 #222222);"
				"}")
			else:
				self.startButton3.setEnabled(True)
				self.startButton3.setStyleSheet(
				"QPushButton {"
				"border: 1px solid #199909;"
				"border-radius: 6px;"
				"background-color: #116a06;"
				"background-color: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 0.67, "
				"stop: 0 #22c70d, stop: 1 #116a06);"
				"}"
				"QPushButton:pressed {"
				"border: 1px solid #333333;"
				"background-color: #222222;"
				"background-color: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 0.67, "
				"stop: 0 #444444, stop: 1 #222222);"
				"}")

	def togglePause1(self):
		global pause1
		if self.timeRemaining1.text() != "00:00:00":
			if self.Timer1.isActive():
				self.Timer1.stop()
				self.timeRemaining1.setStyleSheet("QPushButton { background : #FF6600; color : white; border-width: 1px; \
								   border-color: #FD9A59 ; border-radius: 9px; border-style: outset; }")
				pause1 = True
			else:
				if pause1:
					self.Timer1.start()
					self.timeRemaining1.setStyleSheet("QPushButton { background : #21610B; color : white; border-width: 1px; \
									   border-color: #3E8F23 ; border-radius: 9px; border-style: outset; }")
					pause1 = False
		elif Sound:
			Playbin2.set_state(gst.STATE_NULL)  # for gstreamer
			os.system("dbus-send --type=method_call --dest=com.nokia.mafw.renderer.Mafw-Gst-Renderer-Plugin.gstrenderer /com/nokia/mafw/renderer/gstrenderer \
				com.nokia.mafw.extension.set_extension_property string:volume variant:uint32:"+str(defaultVolume))
			if playstate == 1:
				os.popen("dbus-send --dest=com.nokia.mafw.renderer.Mafw-Gst-Renderer-Plugin.gstrenderer /com/nokia/mafw/renderer/gstrenderer com.nokia.mafw.renderer.resume")

	def togglePause2(self):
		global pause2
		if self.timeRemaining2.text() != "00:00:00":
			if self.Timer2.isActive():
				self.Timer2.stop()
				self.timeRemaining2.setStyleSheet("QPushButton { background : #FF6600; color : white; border-width: 1px; \
								   border-color: #FD9A59 ; border-radius: 9px; border-style: outset; }")
				pause2 = True
			else:
				if pause2:
					self.Timer2.start()
					self.timeRemaining2.setStyleSheet("QPushButton { background : #21610B; color : white; border-width: 1px; \
									   border-color: #3E8F23 ; border-radius: 9px; border-style: outset; }")
					pause2 = False
		elif Sound:
			Playbin2.set_state(gst.STATE_NULL)  # for gstreamer
			os.system("dbus-send --type=method_call --dest=com.nokia.mafw.renderer.Mafw-Gst-Renderer-Plugin.gstrenderer /com/nokia/mafw/renderer/gstrenderer \
				com.nokia.mafw.extension.set_extension_property string:volume variant:uint32:"+str(defaultVolume))
			if playstate == 1:
				os.popen("dbus-send --dest=com.nokia.mafw.renderer.Mafw-Gst-Renderer-Plugin.gstrenderer /com/nokia/mafw/renderer/gstrenderer com.nokia.mafw.renderer.resume")

	def togglePause3(self):
		global pause3
		if self.timeRemaining3.text() != "00:00:00":
			if self.Timer3.isActive():
				self.Timer3.stop()
				self.timeRemaining3.setStyleSheet("QPushButton { background : #FF6600; color : white; border-width: 1px; \
								   border-color: #FD9A59 ; border-radius: 9px; border-style: outset; }")
				pause3 = True
			else:
				if pause3:
					self.Timer3.start()
					self.timeRemaining3.setStyleSheet("QPushButton { background : #21610B; color : white; border-width: 1px; \
									   border-color: #3E8F23 ; border-radius: 9px; border-style: outset; }")
					pause3 = False
		elif Sound:
			Playbin2.set_state(gst.STATE_NULL)  # for gstreamer
			os.system("dbus-send --type=method_call --dest=com.nokia.mafw.renderer.Mafw-Gst-Renderer-Plugin.gstrenderer /com/nokia/mafw/renderer/gstrenderer \
				com.nokia.mafw.extension.set_extension_property string:volume variant:uint32:"+str(defaultVolume))
			if playstate == 1:
				os.popen("dbus-send --dest=com.nokia.mafw.renderer.Mafw-Gst-Renderer-Plugin.gstrenderer /com/nokia/mafw/renderer/gstrenderer com.nokia.mafw.renderer.resume")

class Gstreamer_play:

	def __init__(self):
		# Setting the pulsesink's event.id to "ringtone-preview". This way, your program gets added
		# to the player group automatically without having to modify xpolicy.conf
		proplist = pa_proplist_new()
		pa_proplist_sets (proplist, "event.id", "ringtone-preview")
		self.pulsesink = gst.element_factory_make("pulsesink", "shit")

		g_object_set(c_void_p(hash(self.pulsesink)), "proplist", proplist, None)
		Playbin2.set_property("audio-sink", self.pulsesink)

		bus = Playbin2.get_bus()
		bus.add_signal_watch()
		bus.connect("message", self.on_message)

	def on_message(self, bus, message):
		t = message.type
		if t == gst.MESSAGE_EOS:
			Playbin2.set_state(gst.STATE_NULL)
			self.playmode = False
			os.system("dbus-send --type=method_call --dest=com.nokia.mafw.renderer.Mafw-Gst-Renderer-Plugin.gstrenderer /com/nokia/mafw/renderer/gstrenderer \
				com.nokia.mafw.extension.set_extension_property string:volume variant:uint32:"+str(defaultVolume))
			if playstate == 1:
				os.popen("dbus-send --dest=com.nokia.mafw.renderer.Mafw-Gst-Renderer-Plugin.gstrenderer /com/nokia/mafw/renderer/gstrenderer com.nokia.mafw.renderer.resume")
		elif t == gst.MESSAGE_ERROR:
			Playbin2.set_state(gst.STATE_NULL)
			err, debug = message.parse_error()
			print "Error: %s" % err, debug
			self.playmode = False

	def start(self):
		if os.path.isfile(Alarmfile):
			self.playmode = True
			Playbin2.set_property("uri", "file://" + Alarmfile)
			Playbin2.set_state(gst.STATE_PLAYING)

class TimePickDialog(QWidget):
	def __init__(self,parent):
		super(TimePickDialog, self).__init__(parent)
		self.d = QDialog(self)
		self.d.setMinimumHeight(680)
		self.d.setMaximumHeight(680)
		if Language == "nl_NL":
			self.d.setWindowTitle("| uren | minuten | seconden |")
			self.doneButton = QPushButton(self.tr("Voltooid"))
		else:
			self.d.setWindowTitle("| hours | minutes | seconds |")
			self.doneButton = QPushButton(self.tr("Done"))
		hbox = QGridLayout() 
		self.horizontalLayout = QGridLayout() 
		self.hourWidget = QListWidget()
		self.minuteWidget = QListWidget()
		self.secondWidget = QListWidget()
		# performance optimalization in case widget have a uniform size
		self.hourWidget.setUniformItemSizes(True)
		self.minuteWidget.setUniformItemSizes(True)
		self.secondWidget.setUniformItemSizes(True)
		f = QFont()
		f.setPointSize(24)
		global secondsPicked0
		global minutesPicked0
		global hoursPicked0
		global secondsPicked1
		global minutesPicked1
		global hoursPicked1
		global secondsPicked2
		global minutesPicked2
		global hoursPicked2
		global secondsPicked3
		global minutesPicked3
		global hoursPicked3
		global currSelector

		for i in range(49):
			item = QListWidgetItem("%02i" % i)
			item.setFont(f)
			item.setTextAlignment(Qt.AlignCenter)
			self.hourWidget.addItem(item)

		for i in range(60):
			item = QListWidgetItem("%02i" % i)
			item.setFont(f)
			item.setTextAlignment(Qt.AlignCenter)
			self.minuteWidget.addItem(item)

		for i in range(60):
			item = QListWidgetItem("%02i" % i)
			item.setFont(f)
			item.setTextAlignment(Qt.AlignCenter)
			self.secondWidget.addItem(item)

		# set time
		if currSelector == 0:
			self.hourWidget.setCurrentRow(int(hoursPicked0))
			self.minuteWidget.setCurrentRow(int(minutesPicked0))
			self.secondWidget.setCurrentRow(int(secondsPicked0))
		if currSelector == 1:
			self.hourWidget.setCurrentRow(int(hoursPicked1))
			self.minuteWidget.setCurrentRow(int(minutesPicked1))
			self.secondWidget.setCurrentRow(int(secondsPicked1))
		if currSelector == 2:
			self.hourWidget.setCurrentRow(int(hoursPicked2))
			self.minuteWidget.setCurrentRow(int(minutesPicked2))
			self.secondWidget.setCurrentRow(int(secondsPicked2))
		if currSelector == 3:
			self.hourWidget.setCurrentRow(int(hoursPicked3))
			self.minuteWidget.setCurrentRow(int(minutesPicked3))
			self.secondWidget.setCurrentRow(int(secondsPicked3))

		self.horizontalLayout.addWidget(self.hourWidget,0,0) 
		self.horizontalLayout.addWidget(self.minuteWidget,0,1) 
		self.horizontalLayout.addWidget(self.secondWidget,0,2) 
		screenGeometry = QApplication.desktop().screenGeometry()
		if screenGeometry.width() > screenGeometry.height():
			# landscape
			self.horizontalLayout.addWidget(self.doneButton,0,3,Qt.AlignBottom)
			self.doneButton.setMinimumWidth(170)
			self.hourWidget.scrollToItem(self.hourWidget.currentItem(),QAbstractItemView.PositionAtTop)
			self.minuteWidget.scrollToItem(self.minuteWidget.currentItem(),QAbstractItemView.PositionAtTop)
			self.secondWidget.scrollToItem(self.secondWidget.currentItem(),QAbstractItemView.PositionAtTop)
		else:
			# portrait
			self.horizontalLayout.addWidget(self.doneButton,1,0,1,3)
			self.hourWidget.scrollToItem(self.hourWidget.currentItem(),QAbstractItemView.PositionAtCenter)
			self.minuteWidget.scrollToItem(self.minuteWidget.currentItem(),QAbstractItemView.PositionAtCenter)
			self.secondWidget.scrollToItem(self.secondWidget.currentItem(),QAbstractItemView.PositionAtCenter)
		self.connect(QApplication.desktop(), SIGNAL("resized(int)"), self.orientationChanged)
		self.d.setLayout(hbox)
		hbox.addLayout (self.horizontalLayout,0,0)
		self.connect(self.doneButton, SIGNAL("clicked()"), self.accept)
		self.d.exec_()

	def accept(self):
		global secondsPicked0
		global minutesPicked0
		global hoursPicked0
		global secondsPicked1
		global minutesPicked1
		global hoursPicked1
		global secondsPicked2
		global minutesPicked2
		global hoursPicked2
		global secondsPicked3
		global minutesPicked3
		global hoursPicked3
		global currSelector
		if currSelector == 0:
			hoursPicked0 = self.hourWidget.currentRow()
			minutesPicked0 = self.minuteWidget.currentRow()
			secondsPicked0 = self.secondWidget.currentRow()
		if currSelector == 1:
			hoursPicked1 = self.hourWidget.currentRow()
			minutesPicked1 = self.minuteWidget.currentRow()
			secondsPicked1 = self.secondWidget.currentRow()
		if currSelector == 2:
			hoursPicked2 = self.hourWidget.currentRow()
			minutesPicked2 = self.minuteWidget.currentRow()
			secondsPicked2 = self.secondWidget.currentRow()
		if currSelector == 3:
			hoursPicked3 = self.hourWidget.currentRow()
			minutesPicked3 = self.minuteWidget.currentRow()
			secondsPicked3 = self.secondWidget.currentRow()
		self.d.close()

	def orientationChanged(self):
		screenGeometry = QApplication.desktop().screenGeometry()
		if screenGeometry.width() > screenGeometry.height():
			# landscape
			self.d.setMinimumHeight(680)
			self.d.setMaximumHeight(680)
			self.hourWidget.scrollToItem(self.hourWidget.currentItem(),QAbstractItemView.PositionAtTop)
			self.minuteWidget.scrollToItem(self.minuteWidget.currentItem(),QAbstractItemView.PositionAtTop)
			self.secondWidget.scrollToItem(self.secondWidget.currentItem(),QAbstractItemView.PositionAtTop)
			self.horizontalLayout.removeWidget(self.doneButton)
			self.horizontalLayout.addWidget(self.doneButton,0,3,Qt.AlignBottom)
			self.doneButton.setMinimumWidth(170)
		else:
			# portrait
			self.d.resize(680,740)
			self.d.setMinimumHeight(680)
			self.d.setMaximumHeight(680)
			self.hourWidget.scrollToItem(self.hourWidget.currentItem(),QAbstractItemView.PositionAtCenter)
			self.minuteWidget.scrollToItem(self.minuteWidget.currentItem(),QAbstractItemView.PositionAtCenter)
			self.secondWidget.scrollToItem(self.secondWidget.currentItem(),QAbstractItemView.PositionAtCenter)
			self.horizontalLayout.removeWidget(self.doneButton)
			self.horizontalLayout.addWidget(self.doneButton,1,0,1,3)


class DishPickDialog(QWidget):
	def __init__(self,parent):
		super(DishPickDialog, self).__init__(parent)
		self.d = QDialog(self)
		self.d.setMinimumHeight(680)
		self.d.setMaximumHeight(680)
		if Language == "nl_NL":
			self.d.setWindowTitle("Kies gerecht")
		else:
			self.d.setWindowTitle("Choose dish")
		hbox = QGridLayout() 
		horizontalLayout = QGridLayout() 
		self.dishWidget = QListWidget()

		dish_items = load_dishes(self)

		for gerecht in dish_items:
			item = QListWidgetItem(gerecht[0])
			item.setTextAlignment(Qt.AlignCenter)
			self.dishWidget.addItem(item)

		horizontalLayout.addWidget(self.dishWidget,0,0) 
		screenGeometry = QApplication.desktop().screenGeometry()

		self.connect(QApplication.desktop(), SIGNAL("resized(int)"), self.orientationChanged)
		self.d.setLayout(hbox)
		hbox.addLayout (horizontalLayout,0,0)

		self.connect(self.dishWidget, SIGNAL("itemClicked(QListWidgetItem *)"), self.itemClicked)
		self.d.exec_()

	def itemClicked(self, item):
		global currSelector
		global dishName1
		global dishName1banner
		global dishPicked1Nbr
		global dishName2
		global dishPicked2Nbr
		global dishName3
		global dishPicked3Nbr
		if currSelector == 1:
			dishPicked1Nbr = self.dishWidget.currentRow()
			dishName1 = item.text()
		if currSelector == 2:
			dishPicked2Nbr = self.dishWidget.currentRow()
			dishName2 = item.text()
		if currSelector == 3:
			dishPicked3Nbr = self.dishWidget.currentRow()
			dishName3 = item.text()
		self.d.close()

	def orientationChanged(self):
		screenGeometry = QApplication.desktop().screenGeometry()
		if screenGeometry.width() > screenGeometry.height():
			# landscape
			self.d.setMinimumHeight(680)
			self.d.setMaximumHeight(680)
			self.dishWidget.scrollToItem(self.dishWidget.currentItem(),QAbstractItemView.PositionAtTop)
		else:
			# portrait
			self.d.resize(680,740)
			self.d.setMinimumHeight(680)
			self.d.setMaximumHeight(680)
			self.dishWidget.scrollToItem(self.dishWidget.currentItem(),QAbstractItemView.PositionAtCenter)

class extItemWindow(QWidget):
	def __init__(self,parent):
		super(extItemWindow, self).__init__(parent)
		self.wg = QDialog(self)
		self.wg.resize(398, 360)
		self.wg.setWindowTitle(globals()['ItemName%s' % rowNbr].text())

		self.grid2 = QGridLayout()
		grid = QGridLayout()
		scrollingWidget = QWidget()
		scrollingWidget.setLayout(self.grid2)
		 
		self.myScrollArea = QScrollArea()
		self.myScrollArea.setWidgetResizable(True)
		self.myScrollArea.setEnabled(True)
		 
		self.myScrollArea.setWidget(scrollingWidget)
		hbox = QGridLayout()
		hbox.addWidget(self.myScrollArea,0,0,1,2)
		 
		# Layout
		grid = QGridLayout()
		self.wg.setLayout(hbox)
		grid.setHorizontalSpacing(0)
		grid.setVerticalSpacing(0)
		self.defaultItemCheckbox = QCheckBox("set on start",self)
		font = QFont()
		font.setPointSize(15)
		self.defaultItemCheckbox.setFont(font)
		self.cookHintTxt1 = QLineEdit()
		self.cookHintTxt2 = QLineEdit()
		self.cookHintTxt3 = QLineEdit()
		self.cookHintTxt1.setPlaceholderText("Message")
		self.cookHintTxt2.setPlaceholderText("Message")
		self.cookHintTxt3.setPlaceholderText("Message")
		hbox.addWidget(self.cookHintTxt1,0,0,1,2)
		hbox.addWidget(self.cookHintTxt2,1,0,1,2)
		hbox.addWidget(self.cookHintTxt3,2,0,1,2)
		if Language == "nl_NL":
			self.cooktime1 = QMaemo5ValueButton("tijd")
			self.cooktime2 = QMaemo5ValueButton("tijd")
			self.cooktime3 = QMaemo5ValueButton("tijd")
		else:
			self.cooktime1 = QMaemo5ValueButton("time")
			self.cooktime2 = QMaemo5ValueButton("time")
			self.cooktime3 = QMaemo5ValueButton("time")
		self.cooktime1.setValueLayout(QMaemo5ValueButton.ValueUnderTextCentered)
		self.cooktime2.setValueLayout(QMaemo5ValueButton.ValueUnderTextCentered)
		self.cooktime3.setValueLayout(QMaemo5ValueButton.ValueUnderTextCentered)
		self.cooktime1.setValueText("00:00:00")
		self.cooktime2.setValueText("00:00:00")
		self.cooktime3.setValueText("00:00:00")
		hbox.addWidget(self.cooktime1,0,2)
		hbox.addWidget(self.cooktime2,1,2)
		hbox.addWidget(self.cooktime3,2,2)
		clearButton1 = QPushButton()
		clearButton1.setMaximumWidth(50)
		clearButton1.setIcon(QIcon.fromTheme("general_close"))
		clearButton1.setStyleSheet("background: transparent; border: none")
		clearButton2 = QPushButton()
		clearButton2.setIcon(QIcon.fromTheme("general_close"))
		clearButton2.setStyleSheet("background: transparent; border: none")
		clearButton3 = QPushButton()
		clearButton3.setIcon(QIcon.fromTheme("general_close"))
		clearButton3.setStyleSheet("background: transparent; border: none")
		hbox.addWidget(clearButton1,0,3)
		hbox.addWidget(clearButton2,1,3)
		hbox.addWidget(clearButton3,2,3)
		hbox.addWidget(self.defaultItemCheckbox,4,0)
		# test if we have startup dish
		startDishfile = codecs.open(Cooktimer_StartItems,"r", encoding="utf-8")
		data = startDishfile.readlines()
		startDishfile.close()
		num_lines = sum(1 for line in open(Cooktimer_StartItems))
		for count in range(0,num_lines):
			if data[count].strip() == globals()['ItemName%s' % rowNbr].text():
				self.defaultItemCheckbox.setChecked(True)
		
		alarmTxt = QLabel("<b>Alarm</b>")
		alarmTxt.setStyleSheet("qproperty-alignment: 'AlignCenter|AlignRight';")
		hbox.addWidget(alarmTxt,4,1)
		timetext = globals()['timeSel%s' % rowNbr].valueText()
		hbox.addWidget(QLabel("<center>"+timetext+"</center>"),4,2)
		if Language == "nl_NL":
			self.saveItemButton = QPushButton("Gereed",self)
		else:
			self.saveItemButton = QPushButton("Done",self)
		hbox.addWidget(self.saveItemButton,5,0,1,4)
		self.wg.show()
		hh_mi_ss = globals()['timeSel%s' % rowNbr].valueText().split(':',2)
		allInfo = globals()['timeSel%s' % rowNbr].statusTip().split('|')
		if len(allInfo) > 1:
			self.cookHintTxt1.setText(allInfo[1])
			self.cooktime1.setValueText(allInfo[2])
		if len(allInfo) > 3:
			self.cookHintTxt2.setText(allInfo[3])
			self.cooktime2.setValueText(allInfo[4])
		if len(allInfo) > 5:
			self.cookHintTxt3.setText(allInfo[5])
			self.cooktime3.setValueText(allInfo[6])

		self.connect(self.cooktime1, SIGNAL("clicked()"),self.TimeSel1)
		self.connect(self.cooktime2, SIGNAL("clicked()"),self.TimeSel2)
		self.connect(self.cooktime3, SIGNAL("clicked()"),self.TimeSel3)
		self.connect(clearButton1, SIGNAL("clicked()"),self.Clear1)
		self.connect(clearButton2, SIGNAL("clicked()"),self.Clear2)
		self.connect(clearButton3, SIGNAL("clicked()"),self.Clear3)
		self.connect(self.saveItemButton, SIGNAL("clicked()"),self.Saveitems)

	def Clear1(self):
			self.cookHintTxt1.clear()
			self.cooktime1.setValueText("00:00:00")

	def Clear2(self):
			self.cookHintTxt2.clear()
			self.cooktime2.setValueText("00:00:00")

	def Clear3(self):
			self.cookHintTxt3.clear()
			self.cooktime3.setValueText("00:00:00")

	def TimeSel1(self):
		global secondsPicked0
		global minutesPicked0
		global hoursPicked0
		global currSelector

		currSelector = 0
		hh_mi_ss = self.cooktime1.valueText().split(':',2)
		hoursPicked0 = hh_mi_ss[0]
		minutesPicked0 = hh_mi_ss[1]
		secondsPicked0 = hh_mi_ss[2]

		timePick = TimePickDialog(self)
		timePick.show()  
		hours = '%02d' % int(hoursPicked0)
		minutes = '%02d' % int(minutesPicked0)
		seconds = '%02d' % int(secondsPicked0)
		timestring = hours + ":" + minutes + ":" + seconds
		self.cooktime1.setValueText(timestring)

	def TimeSel2(self):
		global secondsPicked0
		global minutesPicked0
		global hoursPicked0
		global currSelector

		currSelector = 0
		hh_mi_ss = self.cooktime2.valueText().split(':',2)
		hoursPicked0 = hh_mi_ss[0]
		minutesPicked0 = hh_mi_ss[1]
		secondsPicked0 = hh_mi_ss[2]

		timePick = TimePickDialog(self)
		timePick.show()  
		hours = '%02d' % int(hoursPicked0)
		minutes = '%02d' % int(minutesPicked0)
		seconds = '%02d' % int(secondsPicked0)
		timestring = hours + ":" + minutes + ":" + seconds
		self.cooktime2.setValueText(timestring)

	def TimeSel3(self):
		global secondsPicked0
		global minutesPicked0
		global hoursPicked0
		global currSelector

		currSelector = 0
		hh_mi_ss = self.cooktime3.valueText().split(':',2)
		hoursPicked0 = hh_mi_ss[0]
		minutesPicked0 = hh_mi_ss[1]
		secondsPicked0 = hh_mi_ss[2]

		timePick = TimePickDialog(self)
		timePick.show()  
		hours = '%02d' % int(hoursPicked0)
		minutes = '%02d' % int(minutesPicked0)
		seconds = '%02d' % int(secondsPicked0)
		timestring = hours + ":" + minutes + ":" + seconds
		self.cooktime3.setValueText(timestring)

	def Saveitems(self):
		total_time = int(globals()['timeSel%s' % rowNbr ].valueText().replace(":", ""))
		subtime1 = int(self.cooktime1.valueText().replace(":", ""))
		subtime2 = int(self.cooktime2.valueText().replace(":", ""))
		subtime3 = int(self.cooktime3.valueText().replace(":", ""))
		if ( subtime1 >= total_time or subtime2 >= total_time or subtime3 >= total_time ):
			os.system('run-standalone.sh dbus-send --type=method_call --dest=org.freedesktop.Notifications  \
				/org/freedesktop/Notifications org.freedesktop.Notifications.SystemNoteInfoprint \
				string:"Message time larger then alarm time!"')
			return
		try:
			file = codecs.open(Cooktimer_ItemFile,"r", encoding="utf-8")
		except:
			QMessageBox.critical(self, "Warning",  "Cannot read " + Cooktimer_ItemFile)	
		# read a list of lines into data
		data = file.readlines()
		data.sort(lambda a, b: cmp(a.upper(), b.upper()))
		file.close()
		num_lines = sum(1 for line in open(Cooktimer_ItemFile))
		newItemFile = codecs.open(Cooktimer_ItemFile,"r", encoding="utf-8")
		for count in range(1,num_lines+1):
			if count == rowNbr:
				newLine = globals()['ItemName%s' % rowNbr ].text() + "|" + globals()['timeSel%s' % rowNbr ].valueText()
				if (self.cooktime1.valueText() != "00:00:00" and self.cookHintTxt1.text() != "" ):
					newLine = newLine + "|" + self.cookHintTxt1.text() + "|" + self.cooktime1.valueText()
				if (self.cooktime2.valueText() != "00:00:00" and self.cookHintTxt2.text() != "" ):
					newLine = newLine + "|" + self.cookHintTxt2.text() + "|" + self.cooktime2.valueText()
				if (self.cooktime3.valueText() != "00:00:00" and self.cookHintTxt3.text() != "" ):
					newLine = newLine + "|" + self.cookHintTxt3.text() + "|" + self.cooktime3.valueText()
				data[rowNbr-1] = newLine + "\n"
		newItemFile.close()
		try:
			file = codecs.open(Cooktimer_ItemFile,"w", encoding="utf-8")
		except:
			QMessageBox.critical(self, "Warning",  "Cannot write " + Cooktimer_ItemFile)	
		newTip = "|".join(data[rowNbr-1].split("|")[1:]).replace("\n", "")+"\n"
		globals()['timeSel%s' % rowNbr].setStatusTip(newTip)
		data = "".join(data)
		file.write(data)
		file.close()
		# update startup dishes
		# we only store the dishname
		newLine = newLine.split("|")[0].strip()
		file = codecs.open(Cooktimer_StartItems,"r", encoding="utf-8")
		data = file.readlines()
		num_lines = len(data)
		file.close()
		if num_lines == 0 and self.defaultItemCheckbox.isChecked():
				# file is empty, just write the entry
				file = codecs.open(Cooktimer_StartItems,"a", encoding="utf-8")
				file.write(newLine + "\n")
				file.close()
		if num_lines > 0 and num_lines < 3 and self.defaultItemCheckbox.isChecked():
			# we can append if dish does not exits
			match = False
			for count in range(0,num_lines):
				# match the dish itself
				if data[count].strip() == newLine:
					match = True
			if not match:
				file.close()
				file = codecs.open(Cooktimer_StartItems,"a", encoding="utf-8")
				file.write(newLine + "\n")

			file.close()
		if num_lines > 2 and self.defaultItemCheckbox.isChecked():
			os.system('run-standalone.sh dbus-send --type=method_call --dest=org.freedesktop.Notifications  \
				/org/freedesktop/Notifications org.freedesktop.Notifications.SystemNoteInfoprint \
				string:"Max of 3 presets already used!"')
			return
		if not self.defaultItemCheckbox.isChecked():
			# check if dish should be removed
			for count in range(0,num_lines):
				# match the dish itself
				if data[count].strip() == newLine:
					data[count] = ""
					file = codecs.open(Cooktimer_StartItems,"w", encoding="utf-8")
					data = "".join(data)
					file.write(data)
					file.close()
		
		os.system('run-standalone.sh dbus-send --type=method_call --dest=org.freedesktop.Notifications  \
			/org/freedesktop/Notifications org.freedesktop.Notifications.SystemNoteInfoprint \
			string:"Messages are successfully saved"')
		self.wg.close()
 
if __name__ == '__main__':
	# QApplication controls things relating to a Qt application, like the main loop.
	# You should always instantiate it before using any QtGui related stuff.
	# See also:
	#   http://doc.trolltech.com/4.6/qapplication.html
	app = QApplication(sys.argv)

	# Create an instance (calling __init__, too, of course) of our window subclassing QWidget
	w = MyMainWindow()

	# Show our window
	w.show()

	# Main event loop of Qt. This won't return until the program exits.
	app.exec_()
	sys.exit()
