Newer
Older
Import / projects / LGN-IP3870 / t / orig / menu.py
# -*- coding: utf-8 -*-
import runtime, uiconfig, config, baseui, utils, model, ui, time, controls, entry
from basemodel import ListStage, Stage, NotifyStage, SymbolSelectionStage, OkNoStage, YesNoStage, EntryStage, PINInputStage,ListTimeStage,ListCalendarStage
from setting import setting
from vdcisetting import vdci_setting
from phonebook import PhoneBookStage, DeletePhoneBookStage
import status
import phonesetting
import os
from roxiadebug import *
#from alarmdb import alarmdb
from tupsetting import tup_setting

from calendardb import calendardb
from tupsetting import tup_setting
from alarmdb import alarmdb
from tdeservice import CallForwardingStage, DoNotDisturbStage, \
	CallerIDBlockingStage, CallerIDUnblockingStage, \
	SpeedDial8Stage, SpeedDial8SettingStage, \
	VideoSupervisionPINCheckStage, NetworkVoiceMailStage, HideIDStage, \
	RejectionCallStage

from myannapp import MyAnnStage
from runtime import mmiDebug as MD
import newprof
import errorcode


class MessageStage(ListStage):
	name = 'messagestage'
	title = _('MESSAGES')
	titleimage = uiconfig.title_message
	icon = uiconfig.message_icon
	domonitor_forbidden = True	
	def __init__(self):
		from profile import profile
		if profile.get_profile()  == 0:
			self.choice = (_('SMS'),_('MMS'),_('Template'),_('Delete'), _('Settings'))
			ListStage.__init__(self, choice=self.choice, title=self.title, titleimage=self.titleimage)
		else:
			self.choice = (_('SMS'),_('Template'))
			ListStage.__init__(self, choice=self.choice, title=self.title, titleimage=self.titleimage, left=_('OK'), right=_('BACK'), isactivate2=False)

	def activate(self, index):
		from profile import profile
		import message
		stage = message.get_stage(index)
		runtime.manager.stack_stage(stage)

class CallLogStage(ListStage):
	titleimage = uiconfig.title_calllog
	icon = uiconfig.call_log_icon

	def __init__(self):
		self.title = _('CALL HISTORY')
		self.choice = (_('Missed calls'), _('Received calls'), _('Dialed calls'), _('Delete calls'))
	
		ListStage.__init__(self)

	

	def activate(self, index):
		import calllog
		stage = calllog.get_stage(index)
		runtime.manager.stack_stage(stage)

class PhoneSettingStage(ListStage):
	
	icon = uiconfig.setting_phone_icon
	name = 'phone setting'
	index = 0

	def __init__(self):
		self.title = _('PHONE SETTINGS')
		self.choice_pstn = (_('Call barring'), _('Display'), _('Menu language'), _('Writing mode'))
		self.choice_ip = (_('Call barring'), _('Display'), _('Menu language'), _('Writing mode'), _('Prefix setting'), _('Outgoing restrict'), _('Incoming restrict') )

		import profile
		if profile.ip_mode == 0:
			self.choice = self.choice_pstn
		else:
			self.choice = self.choice_ip
		ListStage.__init__(self, choice=self.choice, title=self.title, icon=self.icon)

	def show(self):
		self.change_choice(self.choice)
		ListStage.show(self)
		self.ui.set_focus(self.index)

	def activate(self, index):
		self.index = index
		stage = phonesetting.get_stage_phone(index)
		runtime.manager.stack_stage(stage)


class ServiceStage(ListStage):
	name = 'service stage'
	
	#titleimage = uiconfig.title_tde_service

	icon = uiconfig.TdE_icon

	def __init__(self):
		self.title = _('TOOLS')
		self.choice = (_('Alarm'), _('Calendar'), _('Calculator'), _('World time'))
		ListStage.__init__(self, choice=self.choice, title=self.title)


	def activate(self, index):
		if index == 0:
			#stage = AlarmStage
			import alarm
			status.editing_alarm_index = 0
			stage = alarm.AlarmListStage
		elif index == 1:
			stage = CalendarStage
		#elif index == 2:
		#	stage = AbsenceSettingStage
		elif index == 2:
			stage = CaculatorStage
		elif index == 3:
			stage = WorldTimeStage
		else:
			return
		
		runtime.manager.stack_stage(stage)
		
class AbsenceSettingStage(ListStage):
	icon=uiconfig.absence_setting_icon

	def __init__ (self):
		self.title=_('ABSENCE SETTING')
		self.choice = _('Auto answer setting'), _('Missed call message') #_('Missed call message')

		ListStage.__init__(self)
	def activate (self, index):
		if index == 0:
			stage = AutoAnswerSettingStage
		elif index ==1:
			stage = MissCallMessageStage
		runtime.manager.stack_stage(stage)
		
class AutoAnswerSettingStage(ListStage):
	name ='AutoAnswerSetting'
	def __init__(self):
		ListStage.__init__(self)
		self.ui = baseui.AutoAnswerSettingUI(_('SAVE'),'','',_('BACK'))
		self.player_pid = None	
		if setting.autoAnswer:
			self.ans_ind_1 = 0
		else:
			self.ans_ind_1 = 1

		self.ansmode, self.ans_ind_3 = self.get_play_msg()
		
		self.select1_img = utils.put_image(uiconfig.setting_select_img_r, pos=uiconfig.select1_img_pos)
		self.select1_img.hide()
		self.ui.add(self.select1_img)

		self.select2_img = utils.put_image(uiconfig.setting_select_img, pos=uiconfig.select2_img_pos)
		self.select2_img.hide()
		self.ui.add(self.select2_img)

		#self.select3_img = utils.put_image(uiconfig.setting_select_img, pos=uiconfig.select3_img_pos)
		#self.select3_img.hide()
		#self.ui.add(self.select3_img)

		self.answering = [_('Enable'),_('Disable')]
		#self.anstime = ['10','20','30','40']

		deltay_xxx = uiconfig.worldtime_text_font[1]/2+2
		
		pos1 = 302, 99-deltay_xxx #93
		self.ans1_text = runtime.evas.text(text=self.answering[self.ans_ind_1], pos=pos1, color=uiconfig.worldtime_text_color,\
				font=uiconfig.worldtime_text_font)
		self.ui.add(self.ans1_text)
		self.align_center(self.ans1_text,pos1)

		#pos2 = 262, 133-deltay_xxx #127
		#self.ans2_text = runtime.evas.text(text=self.anstime[ans_ind_2], pos=pos2, color=uiconfig.worldtime_text_color,\
		#	font=uiconfig.worldtime_text_font)
		#self.ui.add(self.ans2_text)

		#pos2 = 282, 133-deltay_xxx #127
		#self.ans_text = runtime.evas.text(text='second', pos=pos2, color=uiconfig.worldtime_text_color,\
		#	font=uiconfig.worldtime_text_font)
		#self.ui.add(self.ans_text)
		
		pos3 = 302, 133-deltay_xxx #127
		self.play_msg = self.ansmode[self.ans_ind_3]
		dot = self.play_msg.rfind('.')
		if dot >= 0:
			p_msg = self.play_msg[:dot]
		self.ans3_text = runtime.evas.text(text=p_msg, pos=pos3, color=uiconfig.worldtime_text_color,\
			font=uiconfig.worldtime_text_font)
		self.ui.add(self.ans3_text)
		self.align_center(self.ans3_text,pos3)
		
	def align_center(self, l, pos):
		x, y = pos
		width,height = l.size
		l.move(x - width/2, y)

	def get_play_msg(self):
		value = setting.autoAnswerMessage
		#value = unicode(value, 'euc-kr').encode('utf-8')
		tmp = []
		tmp = os.listdir(config.auto_answer_dir)
		tmp.sort()
		lists = []
		for name in tmp:
			try:
				name = unicode(name, 'euc-kr').encode('utf-8')
			except:
				pass
			if name.endswith('.wav'):
				lists.append(name)
		try:
			value = unicode(value, 'euc-kr').encode('utf-8')
		except:
			pass
		
		try:
			index = lists.index(value)
		except:
			return lists, 0
			
		return lists, index

	# play해줄 file --> euc-kr 잠시 변환
	def get_current_file(self):
		if not self.play_msg:
			return ''
		try:
			filename = unicode(self.play_msg, 'utf-8').encode('euc-kr')
		except:
			pass
		current_file = config.auto_answer_dir + filename
		return current_file
		
	def play_audio(self):
		if status.phone_status != status.Disconnected:
			return
		audio_file = self.get_current_file()
		if audio_file != '':
			audio_file = audio_file.replace('.wav','.mp3')
			#self.player_pid = utils.player.play(audio_file)
			utils.player.play_stereo(audio_file)

	def stop_audio(self):
		#utils.player.stop(self.player_pid)
		utils.player.stop_ring()
		
	def save(self):
		if self.ans_ind_1 == 0:
			setting.set_autoAnswer(1)
		else:
			setting.set_autoAnswer(0)
		# 현재 self.play_msg - utf-8
		value = unicode(self.play_msg, 'utf-8').encode('euc-kr')
		setting.set_autoAnswerMessage(value)
		
	def set_focus(self,index):
		if index == 0:
			self.select1_img.show()
			self.select1_img.file = uiconfig.image_dir +uiconfig.setting_select_img_r
			self.select2_img.file = uiconfig.image_dir +uiconfig.setting_select_img
		#	self.select3_img.file = uiconfig.image_dir +uiconfig.setting_select_img
		elif index == 1:
			self.select1_img.file = uiconfig.image_dir +uiconfig.setting_select_img
			self.select2_img.file = uiconfig.image_dir +uiconfig.setting_select_img_r
		#	self.select3_img.file = uiconfig.image_dir +uiconfig.setting_select_img
		elif index == 2:
			self.select1_img.file = uiconfig.image_dir +uiconfig.setting_select_img
			self.select2_img.file = uiconfig.image_dir +uiconfig.setting_select_img
		#	self.select3_img.file = uiconfig.image_dir +uiconfig.setting_select_img_r

	def show(self):
		Stage.show(self)
		self.index = 0
		self.set_focus(0)
		
	def destroy(self):
		Stage.destroy(self)		
		self.stop_audio()
		
	def update_select1(self,ans_ind_1):
		self.ans1_text.text_set("%s"%self.answering[ans_ind_1])
		
	def update_select2(self,ans_ind_2):
		self.ans2_text.text_set("%s"%self.anstime[ans_ind_2])
		
	def update_select3(self,ans_ind_3):
		self.stop_audio()
		self.play_msg = self.ansmode[ans_ind_3]
		#self.play_msg = unicode(self.play_msg, 'euc-kr').encode('utf-8')
		dot = self.play_msg.rfind('.')
		if dot >= 0:
			p_msg = self.play_msg[:dot]
		self.ans3_text.text_set("%s"%p_msg)
		self.play_audio()
		
	def handle_key(self,key):
		if key == config.Menu4 or key=='CLR':
			runtime.manager.back_stage()
		elif key == 'Left':
			if self.index == 0:
				self.ans_ind_1 -= 1
				if self.ans_ind_1 < 0:
					self.ans_ind_1  = len(self.answering)-1    
				self.update_select1(self.ans_ind_1)
				return True
			if self.index == 1:
				self.ans_ind_3 -= 1
				if self.ans_ind_3 < 0:
					self.ans_ind_3  = len(self.ansmode)-1    
				self.update_select3(self.ans_ind_3)
				return True
		elif key == 'Right':
			if self.index == 0:
				self.ans_ind_1 += 1
				if self.ans_ind_1 > len(self.answering)-1:
					self.ans_ind_1 = 0	
				self.update_select1(self.ans_ind_1)
				return True
			if self.index ==1:
				self.ans_ind_3 += 1
				if self.ans_ind_3 > len(self.ansmode)-1:
					self.ans_ind_3 = 0	
				self.update_select3(self.ans_ind_3)
				return True
		elif key == 'Down':
			self.index = self.index + 1
			if self.index > 1:
				self.index = 0
			self.set_focus(self.index)
			if self.index == 1:
				self.stop_audio()
				self.play_audio()
			else:
				self.stop_audio()
			return True
		elif key == 'Up':
			self.index = self.index - 1
			if self.index < 0:	
				self.index = 1
			self.set_focus(self.index)
			if self.index == 1:
				self.stop_audio()
				self.play_audio()
			else:
				self.stop_audio()
			return True
		elif key == config.Menu1 or key == 'OK':
			self.save()
			if self.ans_ind_1 == 0:
				runtime.manager.change_stage(NotifyStage(_('Auto answer enabled'),icon = None))
			else:
				runtime.manager.change_stage(NotifyStage(_('Auto answer disabled'),icon = None))
			utils.player.play_effect(config.SETTING_SUCCEEDED)
			
		elif key in (config.OffHook, config.Green):
			self.stop_audio()
			return False
		else:
			return False
		return True
		
		
class  MissCallMessageStage(ListStage): #MCA-Missed Call Alarm
	def __init__(self):
		ListStage.__init__(self)
		self.ui = baseui.MissCallMessageUI(_('SAVE'),'','',_('BACK'))
		
		self.MCA_enable = setting.missedCallAlarm

		'''
		self.select1_img = utils.put_image(uiconfig.setting_select_img_r,pos=uiconfig.select1_img_pos)
		self.select1_img.hide()
		self.ui.add(self.select1_img)

		self.MCA_setting = [_('Disable'), _('Enable')]

		self.MCA_setting_text = runtime.evas.text(text=self.MCA_setting[self.MCA_enable], pos=(0,0), color=uiconfig.worldtime_text_color,\
				font=uiconfig.worldtime_text_font)
		self.ui.add(self.MCA_setting_text)
		self.align_center(self.MCA_setting_text, (302,93))
		'''

		deltay_xxx = uiconfig.worldtime_text_font[1]/2+2

		# MCA On/off
		name, pos = uiconfig.ico_MCA_set
		self.icon_MCA_set = utils.put_image(name, pos)
		MCA_set_text = runtime.evas.text(text=_('SET'),pos=(114,85-deltay_xxx),color=uiconfig.worldtime_text_color,font=uiconfig.worldtime_text_font)
		self.ui.add(MCA_set_text)
		MCA_enable_choose = [_('Disable'), _('Enable')]
		self.MCA_set = controls.ListBox_Control(MCA_enable_choose, setting.missedCallAlarm, font=uiconfig.alarm_font, pos=(210, 69), color=uiconfig.list_text_color, mode=uiconfig.LIST_MODE_MEDIUM)

		# MCA Tel. num 1
		name, pos = uiconfig.ico_MCA_tel1
		self.icon_MCA_tel1 = utils.put_image(name, pos)
		MCA_tel1_text = runtime.evas.text(text=_('Telephone number')+'1', pos=(114,119-deltay_xxx),color=uiconfig.worldtime_text_color,font=uiconfig.worldtime_text_font)
		self.ui.add(MCA_tel1_text)
		self.MCA_tel_num1 = controls.Input_Control(pos=(210,103+2), size=(184,28))
		self.MCA_tel_num1.set_automata('123')
		#if setting.missedCallAlarmNumber1 != '':
		self.MCA_tel_num1.set_text(setting.missedCallAlarmNumber1)
		self.MCA_tel_num1.set_max(uiconfig.MAX_INPUT_TEL)
		self.ui.add(self.MCA_tel_num1)

		# MCA Tel. num 2
		name, pos = uiconfig.ico_MCA_tel2
		self.icon_MCA_tel2 = utils.put_image(name, pos)
		MCA_tel2_text = runtime.evas.text(text=_('Telephone number')+'2', pos=(114,153-deltay_xxx),color=uiconfig.worldtime_text_color,font=uiconfig.worldtime_text_font)
		self.ui.add(MCA_tel2_text)
		self.MCA_tel_num2 = controls.Input_Control(pos=(210,137+2), size=(184,28))
		self.MCA_tel_num2.set_automata('123')
		#if setting.missedCallAlarmNumber2 != '':
		self.MCA_tel_num2.set_text(setting.missedCallAlarmNumber2)
		self.MCA_tel_num2.set_max(uiconfig.MAX_INPUT_TEL)
		self.ui.add(self.MCA_tel_num2)

		# MCA Tel. num 3
		name, pos = uiconfig.ico_MCA_tel3
		self.icon_MCA_tel3 = utils.put_image(name, pos)
		MCA_tel3_text = runtime.evas.text(text=_('Telephone number')+'3', pos=(114,187-deltay_xxx),color=uiconfig.worldtime_text_color,font=uiconfig.worldtime_text_font)
		self.ui.add(MCA_tel3_text)
		self.MCA_tel_num3 = controls.Input_Control(pos=(210,171+2), size=(184,28))
		self.MCA_tel_num3.set_automata('123')
		#if setting.missedCallAlarmNumber3 != '':
		self.MCA_tel_num3.set_text(setting.missedCallAlarmNumber3)
		self.MCA_tel_num3.set_max(uiconfig.MAX_INPUT_TEL)
		self.ui.add(self.MCA_tel_num3)

	def destroy(self):
		self.MCA_set.free()
		self.icon_MCA_set.free()
		self.icon_MCA_tel1.free()
		self.icon_MCA_tel2.free()
		self.icon_MCA_tel3.free()
		Stage.destroy(self)

	def align_center(self, l, pos):
		x, y = pos
		width,height = l.size
		l.move(x - width/2, y)
		
	def set_focus(self,index):
		if index == 0:
			self.MCA_set.showFocus()
			self.MCA_tel_num1.lostFocus()
			self.MCA_tel_num2.lostFocus()
			self.MCA_tel_num3.lostFocus()
		elif index == 1:
			self.MCA_set.lostFocus()
			self.MCA_tel_num1.showFocus()
			self.MCA_tel_num2.lostFocus()
			self.MCA_tel_num3.lostFocus()
		elif index == 2:
			self.MCA_set.lostFocus()
			self.MCA_tel_num1.lostFocus()
			self.MCA_tel_num2.showFocus()
			self.MCA_tel_num3.lostFocus()
		elif index == 3:
			self.MCA_set.lostFocus()
			self.MCA_tel_num1.lostFocus()
			self.MCA_tel_num2.lostFocus()
			self.MCA_tel_num3.showFocus()
			
	def show(self):
		Stage.show(self)
		self.index = 0
		self.set_focus(0)
		
	def handle_key(self,key):
		#ret = ListStage.handle_key(self,key)
		if key == config.Menu1 or key == 'OK':
			# enable / disable상태를 체크 
			set_index = self.MCA_set.get_index()
			if set_index != 0:
				# 설정된 번호가 없이 Enable 되는 것을 방지
				if self.MCA_tel_num1.get_text()== '' and self.MCA_tel_num2.get_text() == '' and self.MCA_tel_num3.get_text() == '':
					utils.player.play_effect(config.SETTING_FAILED)
					runtime.manager.change_stage(NotifyStage(_('Please input telephone number first'),icon = None))
					return False

				# 설정된 번호가 중복되어 Enable 되는 것을 방지				
				if ((self.MCA_tel_num1.get_text() == self.MCA_tel_num2.get_text() and self.MCA_tel_num1.get_text()!='') or \
				   (self.MCA_tel_num1.get_text() == self.MCA_tel_num3.get_text() and self.MCA_tel_num1.get_text()!='') or \
				   (self.MCA_tel_num2.get_text() == self.MCA_tel_num3.get_text() and self.MCA_tel_num2.get_text()!='')):
					utils.player.play_effect(config.SETTING_FAILED)
					runtime.manager.change_stage(NotifyStage(_('Duplicated number.'),icon = None))
					return False
					
			setting.missedCallAlarm = set_index
			setting.missedCallAlarmNumber1 = self.MCA_tel_num1.get_text()
			setting.missedCallAlarmNumber2 = self.MCA_tel_num2.get_text()
			setting.missedCallAlarmNumber3 = self.MCA_tel_num3.get_text()
			setting.save()
			utils.player.play_effect(config.SETTING_SUCCEEDED)
			runtime.manager.change_stage(NotifyStage(_('Set is saved'),icon = None))
			return True
		elif key == config.Menu4:
			runtime.manager.back_stage()
			return True
		elif key == config.Red:
			runtime.manager.back_stage('idle')
		elif key == config.LongMenu2:
			if self.index == 1:
				self.MCA_tel_num1.set_text('')
			elif self.index == 2:
				self.MCA_tel_num2.set_text('')
			elif self.index == 3:
				self.MCA_tel_num3.set_text('')
			
		elif key == 'Up':
			self.index -= 1
			if self.index < 0:
				self.index = 3
			self.set_focus(self.index)
		elif key == 'Down':
			self.index += 1
			if self.index > 3:
				self.index = 0
			self.set_focus(self.index)
		elif key == 'Left' or key == 'Right':
			if self.index == 0:
				self.MCA_set.handle_key(key)
				
		elif key in '0123456789':
			if self.index == 1:		self.MCA_tel_num1.handle_key(key)
			elif self.index == 2:	self.MCA_tel_num2.handle_key(key)
			elif self.index == 3:	self.MCA_tel_num3.handle_key(key)
			return True
		elif key == 'CLR':
			if self.index == 1:
				if len(self.MCA_tel_num1.get_text()) > 0:
					self.MCA_tel_num1.handle_key('\b')
				else:
					runtime.manager.back_stage()
			elif self.index == 2:
				if len(self.MCA_tel_num2.get_text()) > 0:
					self.MCA_tel_num2.handle_key('\b')
				else:
					runtime.manager.back_stage()
			elif self.index == 3:
				if len(self.MCA_tel_num3.get_text()) > 0:
					self.MCA_tel_num3.handle_key('\b')
				else:
					runtime.manager.back_stage()
			else	:
				runtime.manager.back_stage()
			return True
			
		'''
		if key == 'Down':
			self.index = self.index + 1
			if self.index > 1:
				self.index = 0
			self.set_focus(self.index)
			return True

		elif key == 'Up':
			self.index = self.index - 1
			if self.index < 0:	
				self.index = 1
			self.set_focus(self.index)
			return True
		'''
		#elif ret:
		#	return ret
		return True
		
class AlarmStage(ListStage):
	name = 'AlarmClock'
	titleimage = uiconfig.Third_title_alarm	
	icon = uiconfig.TdE_icon
	def __init__(self):			
		self.title = _('ALARM CLOCK')
		self.choice = (_('List'), _('Add new'),_('Apply'))		
		ListStage.__init__(self, choice=self.choice, title=self.title, titleimage=self.titleimage)

	def show(self):		
		self.change_choice(self.choice)		
		ListStage.show(self)

	
	def activate(self, index):		
		import alarm
		
		if index == 0:
			stage = alarm.AlarmListStage
			runtime.manager.stack_stage(stage)	
		elif index == 1:
			status.alarm_item = alarmdb.new_item()
			status.alarm_item[0] = str(alarmdb.count())
			status.editing_alarm_index = -1				
			item = status.alarm_item
			stage = alarm.DisplayAlarmStage(item,1)
			runtime.manager.stack_stage(stage)	
		elif index == 2:
			if alarm.alarm_valid():
				setting.set_agenda_time(5*1000, alarm.alarm_activate)
				runtime.manager.back_stage('idle')
			else:
				runtime.manager.stack_stage(AlarmNotifyStage('Alarm invalid!'))
				setting.agenda_delete()
				

#Thang [20080428 - 1] warning
class WarningStage(Stage):	
	def __init__(self):
		self.ui = baseui.WarningUI(_('SAVE'),'','',_('BACK'))	

	def handle_key(self,key):
		ret = self.ui.handle_key(key)
		if key == config.Menu1:
			import alarm
			self.ui.handle_key(key)
			setting.set_warning_time(5*1000, alarm.warning_activate)
			runtime.manager.back_stage('idle')
		return ret
		
	
		
#Thang [20080428 - 1] ================
	

class CaculatorStage(ListStage):	
	subtitle = _('Input')
	name = 'Calculator'
	def __init__(self):
		self.title=_('CALCULATOR')
		ListStage.__init__(self)
		self.tmpkey = runtime.evas.handle_key
		runtime.evas.handle_key = self.handle_key
		self.key_changed = True
		self.start_div_flag = False
		self.div_number = '' # for number after input the div operation
		self.op = ['+','-','/','*']
		self.ind = 0
		self.ui = baseui.CalculatorUI(_('OK'), _('AC'),'',_('BACK'))
		self.ui.entry_1.ascii_mode_case0 = True
		self.ui.set_automata('123',False)
		#self.ui.show_cursor(True)
 		self.equal = runtime.evas.text(text="=", pos=(115,99), color=uiconfig.cal_text_color, font=uiconfig.cal_text_font)
		self.ui.add(self.equal)
		self.re= runtime.evas.text (text="0", color=uiconfig.cal_text_color, font=uiconfig.cal_text_font)
		self.re.pos = uiconfig.result_pos		
		self.ui.add(self.re)
		#pos=(358,99),
		
		pos = uiconfig.button_pos
		#size = uiconfig.button_size
		name = uiconfig.button_name

		index = 0
		self.equal_image = utils.put_image(name[index], pos[index])
		self.equal_image.hide()
		self.ui.add(self.equal_image)

		index+=1
		self.sub_image = utils.put_image(name[index], pos[index])
		self.sub_image.hide()
		self.ui.add(self.sub_image)

		index+=1
		self.minus_image = utils.put_image(name[index], pos[index])
		self.minus_image.hide()
		self.ui.add(self.minus_image)

		index+=1
		self.double_image = utils.put_image(name[index], pos[index])
		self.double_image.hide()
		self.ui.add(self.double_image)

		index+=1
		self.div_image = utils.put_image(name[index], pos[index])
		self.div_image.hide()
		self.ui.add(self.div_image)

		index+=1
		self.star_image = utils.put_image(name[index], pos[index])
		self.star_image.hide()
		self.ui.add(self.star_image)

		index+=1
		self.sharp_image = utils.put_image(name[index], pos[index])
		self.sharp_image.hide()
		self.ui.add(self.sharp_image)

		self.enable_input_digit = False
		self.keypadLightTag = None
		
	def show(self):
		ListStage.show(self)
		self.enable_input_digit = True
		#self.change_handle_key()
		

	def update_softkey1(self,key):
		pos = uiconfig.button_pos
		size = uiconfig.button_size
		if key == 'OK':
			'''
			self.equal_image.file = uiconfig.image_dir +uiconfig.button_name_r[0]
			self.equal_image.pos = pos[0]
			self.equal_image.size = size[0]
			'''
			self.equal_image.free()
			self.equal_image = utils.put_image(uiconfig.image_dir + uiconfig.button_name_r[0], pos[0])
		elif key == 'Left':
			'''
			self.sub_image.file =  uiconfig.image_dir + uiconfig.button_name_r[1]
			self.sub_image.pos = pos[1]
			self.sub_image.size = size[1]
			'''
			self.sub_image.free()
			self.sub_image = utils.put_image(uiconfig.image_dir + uiconfig.button_name_r[1], pos[1])
			
		elif key == 'Right':
			'''
			self.minus_image.file = uiconfig.image_dir + uiconfig.button_name_r[2]
			self.minus_image.pos = pos[2]
			self.minus_image.size = size[2]
			'''
			self.minus_image.free()
			self.minus_image = utils.put_image(uiconfig.image_dir + uiconfig.button_name_r[2], pos[2])
		elif key == 'Up':
			'''
			self.double_image.file = uiconfig.image_dir + uiconfig.button_name_r[3]
			self.double_image.pos = pos[3]
			self.double_image.size = size[3]
			'''
			self.double_image.free()
			self.double_image = utils.put_image(uiconfig.image_dir + uiconfig.button_name_r[3], pos[3])
		elif key == 'Down':
			'''
			self.div_image.file = uiconfig.image_dir + uiconfig.button_name_r[4]
			self.div_image.pos = pos[4]
			self.div_image.size = size[4]
			'''
			self.div_image.free()
			self.div_image = utils.put_image(uiconfig.image_dir + uiconfig.button_name_r[4], pos[4])
		elif key == '*':
			self.star_image.file =  uiconfig.image_dir + uiconfig.button_name_r[5]
			self.star_image.pos = pos[5]
			#self.star_image.size = size[5]
		elif key == '#':
			self.sharp_image.file = uiconfig.image_dir +uiconfig.button_name_r[6]
			self.sharp_image.pos = pos[6]
			#self.sharp_image.size = size[6]
	
	def update_softkey2(self,key):
		pos = uiconfig.button_pos
		size = uiconfig.button_size
		if key == 'OK':
			self.equal_image.file = uiconfig.image_dir +uiconfig.button_name[0]
			print '#######',uiconfig.image_dir
			self.equal_image.pos = pos[0]
			#self.equal_image.size = size[0]
		elif key == 'Left':
			self.sub_image.file =  uiconfig.image_dir + uiconfig.button_name[1]
			self.sub_image.pos = pos[1]
			#self.sub_image.size = size[1]
		elif key == 'Right':
			self.minus_image.file = uiconfig.image_dir + uiconfig.button_name[2]
			self.minus_image.pos = pos[2]
			#self.minus_image.size = size[2]
		elif key == 'Up':
			self.double_image.file = uiconfig.image_dir + uiconfig.button_name[3]
			self.double_image.pos = pos[3]
			#self.double_image.size = size[3]
		elif key == 'Down':
			self.div_image.file = uiconfig.image_dir + uiconfig.button_name[4]
			self.div_image.pos = pos[4]
			#self.div_image.size = size[4]
		elif key == '*':
			self.star_image.file =  uiconfig.image_dir + uiconfig.button_name[5]
			self.star_image.pos = pos[5]
			#self.star_image.size = size[5]
		elif key == '#':
			self.sharp_image.file = uiconfig.image_dir +uiconfig.button_name[6]
			self.sharp_image.pos = pos[6]
			#self.sharp_image.size = size[6]
			
	def result_cal(self,input_string):
		self.kt ='+-*/()'
		i = 0
		s = ''
		if input_string[len(input_string)-1] == '/':
			raise TypeError 

		val_len = 0
		while i < len(input_string):
			if input_string[i] in ('+', '-', '*', '/','(',')'):
				val_len = 0
			else:
				val_len +=1

			# 14자리까지만 입력 가능. 15자리 이상의 숫자가 입력된 경우, 계산 범위 초과를 출력한다
			if val_len >= 15:
				return 99999999999999999999
			
            		if input_string[i] == '/':
                		i = i + 1
                		s = ''
                		while i < len(input_string) and input_string[i] not in self.kt:
                    			s = s + input_string[i]
                    			i = i + 1
                		input_string = input_string.replace('/'+ s,'/float(' + s +')',1)
            		else:
                		i = i + 1

               
		print 'final input_string =', input_string

		ret=eval(input_string)
		return ret

		if s == '0':
			raise ZeroDivisionError 

	def change_handle_key(self):
		if not self.key_changed:
			self.tmpkey = runtime.evas.handle_key
			runtime.evas.handle_key = self.handle_key
			self.key_changed = True

	def rollback_handle_key(self):
		runtime.evas.handle_key = self.tmpkey
		self.key_changed = False
	
	def insert_symbol(self, s):
		before_text = self.ui.get_text()
		self.ui.insert_text(s)
		after_text = self.ui.get_text()
	
	def activate_menu1(self):
		self.cb(self.ui)
		
	def handle_key(self,down,key):
		#print 'CALC handle_key', key, down
		runtime.manager.proc_keypad_light()

		setting.reset_screen_saver_timer()
		
		if down:
			utils.player.play_keytone(key)

		if key == config.OffHook:
			status.missed_call_count = 0
			runtime.manager.handle_offhook()
			return True
		elif key == config.Green:
			status.videocall_byuser = False
			runtime.manager.handle_green()
			return True
		elif key == config.Video:
			if status.phone_status in (status.Disconnected, status.Dialing):
				status.videocall_byuser = True
				runtime.manager.handle_green(isvideokey=True)
			return True
			
		s = self.ui.get_text()
		if not down and (key != 'CLR' and key != config.Menu3): 
			if key in ('Left', 'Right', 'Up', 'Down', '*', '#', 'OK'):
				self.update_softkey2(key)
				return True
			return

		#start_flag = False
		if key == config.Menu1 or key == 'OK':
			if not self.enable_input_digit:
				return True
			try:
				self.update_softkey1(key)
				self.re.hide()
				res_val = self.result_cal(self.ui.get_text())
				if res_val > 99999999999999999:
					result_val = _('exceeding calculation range')
				else:
					result_val = "%5.2f"%(res_val)
					result_val = result_val.replace(',','.')
				self.re.text_set(result_val)
				x,y = uiconfig.result_pos		
				self.edit_pos = x-self.re.horiz_advance_get(),y
				self.re.pos = self.edit_pos 
				self.re.show()
			except ZeroDivisionError :
				self.enable_input_digit = False
				runtime.manager.stack_stage(DivisionNotifyStage(_('Can not divide to 0')))
			except:	
				self.enable_input_digit = False
				runtime.manager.stack_stage(CalNotifyStage(_('Wrong input')))
		elif key == config.Menu2:
			self.ui.entry_1.set_text('')
			self.re.text_set('0')
			self.re.pos =  uiconfig.result_pos
		elif key ==config.Menu3:
			if down:
				def long_key():
					if config.key_debug:
						print 'generate Long CLR key'
					self.handle_key(down, config.CLEAR_LONG)
					self.long_key_tag = None
					return False
				self.long_key_tag = utils.Timer(config.long_key_interval, long_key)
				if self.ui.handle_key(key):
					if len(self.ui.get_text()) == 0:					
						self.re.text_set('0')
						self.re.pos =  uiconfig.result_pos
						self.ui.set_menu3('')
					return True
				return True
			else:
				self.long_key_tag = None
				
		elif key == config.Menu4:
			runtime.manager.back_stage()
		elif key == config.Red:
			runtime.manager.back_stage('idle')
		elif key == 'CLR':
			if not self.enable_input_digit:
				return True
			if down:
				if self.ui.entry_1.length() == 0:
					runtime.manager.back_stage()
				else:
					def long_key():
						if config.key_debug:
							print 'generate Long CLR key'
						self.handle_key(down, config.CLEAR_LONG)
						self.long_key_tag = None
						return False
					self.long_key_tag = utils.Timer(config.long_key_interval, long_key)
					if self.ui.handle_key(key):
						if len(self.ui.get_text()) == 0:					
							self.re.text_set('0')
							self.re.pos =  uiconfig.result_pos
							self.ui.set_menu3('')
						return True
					return True
			else:
				self.long_key_tag = None
			
		elif key == config.CLEAR_LONG:
			self.ui.handle_key(key)
			if len(self.ui.get_text()) == 0:					
				self.re.text_set('0')
				self.re.pos =  uiconfig.result_pos
				self.ui.set_menu3('')
			return True
		elif key == '*':
			if not self.enable_input_digit:
				return True
			self.update_softkey1(key)
			s = self.ui.get_text()
			#if s[len(s) - 1] in self.op:
			#	self.ui.delete_char()
			#	self.ui.update_entry_info()
			self.insert_symbol('(')
			return True
		elif key == '#':
			if not self.enable_input_digit:
				return True
			self.update_softkey1(key)
			s=self.ui.get_text()
			#if s[len(s) - 1] in self.op:
			# 	self.ui.delete_char()
			#	self.ui.update_entry_info()
			self.insert_symbol(')')
			return True
		elif key in ('Left', 'Right', 'Up', 'Down'):
			if not self.enable_input_digit:
				return True
			self.update_softkey1(key)
			s = self.ui.get_text()
			if s == '' :
				return
			elif s[len(s) - 1] in self.op:
			 	self.ui.delete_char()
				self.ui.update_entry_info()
			if key == 'Left':	self.insert_symbol('+')
			elif key == 'Right':	self.insert_symbol('-')
			elif key == 'Up':	self.insert_symbol('*')
			elif key == 'Down':	self.insert_symbol('/')
			return True
		else:
			if self.enable_input_digit:
				result = self.ui.handle_key(key)
				#if key in '0123456789' and self.ui.get_text():
					#if self.start_div_flag:
						#self.div_number += key
					#print '----after div: number=', self.div_number
					#self.ui.def_left = _('OK')
					#self.ui.set_left(_('OK'))
				return result	
		return True
		
	def destroy(self):
		self.rollback_handle_key()
		ListStage.destroy(self)
		self.equal_image.free()
		self.sub_image.free()
		self.minus_image.free()
		self.double_image.free()
		self.div_image.free()
		self.keypadLightTag = None
		

		
class CalNotifyStage(NotifyStage):
	def __init__(self, message,cb=None):
		icon = uiconfig.baloon_setting_voip_icon
		NotifyStage.__init__(self, message, icon, cb)
		
class CalendarNotifyStage(NotifyStage):
	def __init__(self, message,cb=None):
		icon = uiconfig.baloon_phonebook_icon
		NotifyStage.__init__(self, message, icon, cb)
		
class DivisionNotifyStage(NotifyStage):	
	def __init__(self, message,cb=None):
		icon = uiconfig.baloon_setting_voip_icon
		NotifyStage.__init__(self, message, icon, cb)
		
class WorldTimeStage (ListStage):
	def __init__(self):
		ListStage.__init__(self)
		self.ui = baseui.WorldTimeUI(_('LIST'), '','', _('BACK'))
		self.ind_city = 0
		pos = uiconfig.select_city_img_pos
		size = uiconfig.select_city_img_size
		self.select_city_img = utils.put_image(uiconfig.select_city_img_r,pos)
		self.select_city_img.hide()
		self.ui.add(self.select_city_img)
		
		size1 = uiconfig.crossline_img_size
		size2 = uiconfig.verticalline_img_size
		size3 = uiconfig.map_ball_size
		self.pos1 = uiconfig.co_ordinate[self.ind_city][0]
		self.pos2 = uiconfig.co_ordinate[self.ind_city][1]
		self.pos3 =  uiconfig.co_ordinate[self.ind_city][2]
		self.put_line(self.ind_city,self.pos1,size1,self.pos2,size2,self.pos3,size3)
		self._get_time = utils.Timer(3600,self.get_time)
		
		pos = 220 + (len(self.City_time(self.ind_city)[1])*10)/2 + 8, 218
		size = uiconfig.dst_icon_size
		#self.dst_icon = utils.put_image (uiconfig.dst_icon, pos)		
		#self.ui.add(self.dst_icon)
		#self.dst_icon.hide()

	def align_center(self, l, pos):
		x, y = pos
		width,height = l.size
		l.move(x - width/2, y)
		
	def put_line(self,ind_city,pos1,size1,pos2,size2,pos3,size3):
		size1 = uiconfig.crossline_img_size
		size2 = uiconfig.verticalline_img_size
		size3 = uiconfig.map_ball_size
		self.line1 = utils.put_image(uiconfig.crossline_img,self.pos1)
		self.ui.add(self.line1)	
		self.line2 = utils.put_image(uiconfig.verticalline_img,self.pos2)
		self.ui.add(self.line2)	
		self.map_ball = utils.put_image (uiconfig.map_ball,self.pos3)
		self.ui.add(self.map_ball)

		time_display = self.City_time(self.ind_city)[1]
		city_name_display = self.City_time(self.ind_city)[0] 

		self.ct = runtime.evas.text(text="%s"%(time_display),pos=(0,0), \
			color=uiconfig.worldtime_text_color, \
			font=uiconfig.worldtime_text_font)
		self.ui.add(self.ct)
		pos = (240, 218)
		self.align_center(self.ct, pos)

		self.cn = runtime.evas.text (text="%s"%(city_name_display),pos=(0,0),\
				color=uiconfig.worldtime_text_color, \
				font=uiconfig.worldtime_text_font)
		self.ui.add(self.cn)
		pos = (240, 185)
		self.align_center(self.cn, pos)

	def update_line(self,ind_city):
		self.pos1 = uiconfig.co_ordinate[self.ind_city][0]
		self.pos2 = uiconfig.co_ordinate[self.ind_city][1]
		self.pos3 = uiconfig.co_ordinate[self.ind_city][2]
		self.line1.move(self.pos1[0],self.pos1[1])
		self.line2.move(self.pos2[0],self.pos2[1])
		self.map_ball.move(self.pos3[0],self.pos3[1])
		self.cn.text_set("%s"%self.City_time(self.ind_city)[0])
		pos = (240, 185)
		self.align_center(self.cn, pos)
		self.ct.text_set("%s"%self.City_time(self.ind_city)[1])
		pos = (240, 218)
		self.align_center(self.ct, pos)
		
	def display_dst_icon(self,ind_city):		
		#self.dst_icon.show()
		return
	
	def update_select(self,ind_city):
		self.select_city_img.file = uiconfig.image_dir + uiconfig.select_city_img_r
		self.select_city_img.pos = uiconfig.select_city_img_pos
		self.select_city_img.size = uiconfig.select_city_img_size
		pos = uiconfig.dst_icon_pos
		size = uiconfig.dst_icon_size
		
	def City_time(self,ind_city=0):
		import time,ntptime
		sys_time = time.localtime(ntptime.ntime())	
		#lt = ['Mon','Tue','Wed','Thu','Fri','Sat','Sun']
		lt = [_('Mon'), _('Tue'), _('Wed'), _('Thu'), _('Fri'), _('Sat'), _('Sun')]
		self.ind_city = ind_city
		fp = open ('worldtime_table.txt','r')
		self.city = fp.readline().split(',')[:-1]
		add_time = fp.readline().split(',')[:-1]
		self.dst_time =  fp.readline().split(',')[:-1]
		fp.close()
		#print self.city,self.dst_time,add_time ,ind_city
		my_date_summer = self.date_summer(self.dst_time[ind_city],add_time[ind_city])
		sys_month = my_date_summer[1]
		sys_date = my_date_summer[2]
		sys_hour =my_date_summer[3]
		self.sys_minute = my_date_summer[4]
		sys_day = my_date_summer[6]
		# display context
		change_time = int(add_time[ind_city])+int(self.dst_time[ind_city])+9
		if change_time >= 12:
			change_time -= 24
		if change_time >= 0 :
			change_time = '+' + str(change_time)

		# shchun : todo how about use strftime() 
		'''
		if sys_hour == 12:
			str_time ="%02d/%02d(%s) %s %02d:%02d (%s)" %(sys_month, sys_date, lt[sys_day], _('PM'), sys_hour, self.sys_minute, change_time)
		elif sys_hour == 24:
			str_time ="%02d/%02d(%s) %s %02d:%02d (%s)" %(sys_month, sys_date, lt[sys_day], _('AM'), int(sys_hour)/2, self.sys_minute, change_time)
		elif sys_hour < 12 and sys_hour > 0:
			str_time ="%02d/%02d(%s) %s %02d:%02d (%s)" %(sys_month, sys_date, lt[sys_day], _('AM'), int(sys_hour)%12, self.sys_minute, change_time)
		elif sys_hour > 12 and sys_hour < 23:	
			str_time ="%02d/%02d(%s) %s %02d:%02d (%s)" %(sys_month, sys_date, lt[sys_day], _('PM'), int(sys_hour)%12, self.sys_minute, change_time)	
		elif sys_hour < 0:
			sys_hour = (-1)*sys_hour
			str_time ="%02d/%02d(%s) %s %02d:%02d (%s)" %(sys_month, sys_date, lt[sys_day], _('PM'), int(sys_hour)%12, self.sys_minute, change_time)	
		else:
			str_time ="%02d/%02d(%s) %s %02d:%02d (%s)" %(sys_month, sys_date, lt[sys_day], _('PM'), int(sys_hour)%12, self.sys_minute, change_time)	
		'''	
		str_time ="%02d/%02d(%s) %2d:%02d (%s)" %(sys_month, sys_date, lt[sys_day], sys_hour, self.sys_minute, change_time)	

		return self.city[ind_city], str_time
		
	def date_summer(self,add_time,time_dst):
		import time,ntptime
		y, month, d, h, m, s,w = time.localtime(ntptime.ntime())[:7]
		if (h +int(add_time)+ int(time_dst)) > 24:
			w = w + 1
			if w > 6:	w = 0
			d = d + 1
			h = (h +int(add_time)+ int(time_dst)) % 24
			if d > 31 and month in [1,3,5,8,10,12]:
				d = 1
				month = month + 1
				if month > 12:
					month = 1
					y = y + 1
			elif d > 30 and month in [4,6,7,9,11]:
				d = 1
				month = month + 1
			elif d > 28 and y %4 != 0 and month == 2:
				d = 1
				month = month + 1
			elif d > 29 and y %4 == 0 and m == 2:
				d = 1
				month = month + 1
		elif (h +int(add_time)+ int(time_dst)) < 0:
			w = w - 1
			if w < 0:	w = 6
			d = d - 1
			#h = (-1)*(h +int(add_time)+ int(time_dst)) % 24
			h = (h +int(add_time)+ int(time_dst)) % 24
			if d < 1 and month in [2,4,6,9,11]:
				d = 31
				month = month - 1
			if d < 1 and month == 1:
				d = 31
				month = 12
				y = y - 1
			elif d < 1 and month in [5,8,10,12]:
				d = 30
				month = month - 1
			elif d < 1 and y %4 != 0 and month == 3:
				d = 28
				month = month - 1
			elif d <1 and y %4 == 0 and month == 3:
				d = 29
				month = month - 1
		elif (h +int(add_time)+ int(time_dst)) == 0:
			#w = w + 1
			#if w > 6:	w = 0
			#d = d + 1
			h = (h +int(add_time)+ int(time_dst)) + 24
			#h = (h +int(add_time)+ int(time_dst))
			'''
			if d > 31 and month in [1,3,5,8,10,12]:
				d = 1
				month = month + 1
				if month > 12:
					month = 1
					y = y + 1
			elif d > 30 and month in [4,6,7,9,11]:
				d = 1
				month = month + 1
			elif d > 28 and y %4 != 0 and month == 2:
				d = 1
				month = month + 1
			elif d > 29 and y %4 == 0 and m == 2:
				d = 1
				month = month + 1
			'''
		elif (h +int(add_time)+ int(time_dst)) == 12:
			#w = w + 1
			#if w > 6:	w = 0
			#d = d + 1
			h = (h +int(add_time)+ int(time_dst))
		else:
			h = h +int(add_time)+ int(time_dst)
		return y, month, d, h, m, s,w

	def show(self):		
		ListStage.show(self)
		self.ind_city = 0
		#self.display_dst_icon

	def get_time(self):
		self._get_time = utils.Timer(3600,self.get_time)
		self.cn.text_set("%s"%self.City_time(self.ind_city)[0])
		self.ct.text_set("%s"%self.City_time(self.ind_city)[1])
		pos = (240, 218)
		self.align_center(self.ct, pos)
		
	def  handle_key(self, key,flag=False):
		if key == config.Menu1 or key == 'OK':
			index = self.ind_city
			total_city_time = self.get_total_time()			
			runtime.manager.stack_stage(TimeDetailStage(total_city_time,index))
#		elif key == config.Menu2:
#			stage = DSTEnableStage
#			runtime.manager.stack_stage(stage)
		elif key == config.Menu4 or key == 'CLR':
			runtime.manager.back_stage('service stage')
		elif key == config.Red:
			runtime.manager.back_stage('idle')
		elif  key == 'Down' or key == 'Right':		
			self.ind_city +=1
			if self.ind_city > len(self.city)-1:
				self.ind_city = 0
			#self.display_dst_icon(self.ind_city)
			self.update_line(self.ind_city)
			self.update_select(self.ind_city)
		elif  key == 'Up' or key == 'Left':
			self.ind_city -= 1
			if self.ind_city < 0:
				self.ind_city = len(self.city)-1 
			#self.display_dst_icon(self.ind_city)
			self.update_line(self.ind_city)
			self.update_select(self.ind_city)
		else:
			return False
		return True
		
	def destroy(self):
		self._get_time = None
		ListStage.destroy(self)

	def get_total_time(self):
		total_city_time = []
		for i in range(len(self.city)):
			city_time = self.City_time(i)
			total_city_time.append(city_time)
		return total_city_time

class TimeZoneSettingStage (ListStage):
	def __init__(self):
		ListStage.__init__(self)
		setting.ntp_timezone
		
		self.timezone_name = ('GMT-12', 'GMT-11', 'GMT-10', 'GMT-9', \
							'GMT-8', 'GMT-7', 'GMT-6', 'GMT-5', \
							'GMT-4', 'GMT-3', 'GMT-2', 'GMT-1', \
							'GMT', 'GMT+1', 'GMT+2', 'GMT+3', \
							'GMT+4', 'GMT+5', 'GMT+6', 'GMT+7', \
							'GMT+8', 'GMT+9', 'GMT+10', 'GMT+11', 'GMT+12')
		self.timezone = (-12,-11,-10,-9,-8,-7,-6,-5,-4,-3,-2,-1,0, \
					1,2,3,4,5,6,7,8,9,10,11,12)
		self.xcoord = (160,170,180,190,\
					205,215,225,235,\
					250,260,270,0,\
					17,20,25,40,\
					55,70,85,100,\
					110,120,130,140,150)
		self.ui = baseui.WorldTimeUI(_('SET'), '','', _('BACK'),_('TIMEZONE SETTING'))
		self.selindex = self.getTimeZoneIndex(int(setting.ntp_timezone))
		

		# combo box
		pos = uiconfig.select_city_img_pos
		size = uiconfig.select_city_img_size
		self.select_city_img = utils.put_image(uiconfig.select_city_img_r,pos)
		self.select_city_img.hide()
		self.ui.add(self.select_city_img)
		
		size2 = uiconfig.verticalline_img_size
		self.pos2 = self.xcoord[self.selindex]+ 91, 45

		print 'SELINDEX=', self.selindex, ',xcoord=', self.xcoord[self.selindex]
		self.put_line(self.selindex,self.pos2,size2)

	def getTimeZoneIndex(self,tz):
		for i in range(len(self.timezone)):
			if self.timezone[i] == tz:
				return i

		print '### getTimeZoneIndex error'
		return 14 # default : GMT+1
		
									
	def align_center(self, l, pos):
		x, y = pos
		width,height = l.size
		l.move(x - width/2, y)
		
	def put_line(self,selindex,pos2,size2):
		print 'PUT LINE ', selindex
		size2 = uiconfig.verticalline_img_size
		self.line1 = utils.put_image(uiconfig.verticalline_img,self.pos2)
		self.ui.add(self.line1)	
		self.line2 = utils.put_image(uiconfig.verticalline_img,(self.pos2[0]+3, self.pos2[1]))
		self.ui.add(self.line2)

		city_name_display = self.getTimeZone(self.selindex)[0] 
		self.cn = runtime.evas.text (text="%s"%(city_name_display),pos=(0,0),\
				color=uiconfig.worldtime_text_color, \
				font=uiconfig.worldtime_text_font)
		self.ui.add(self.cn)
		pos = (240, 185)
		self.align_center(self.cn, pos)

	def update_line(self,selindex):
		print 'UPDATE LINE ', selindex
		self.pos2 = self.xcoord[self.selindex]+ 91, 45
		self.line1.move(self.pos2[0],self.pos2[1])
		self.line2.move(self.pos2[0]+3,self.pos2[1])
		self.cn.text_set("%s"%self.getTimeZone(self.selindex)[0])
		pos = (240, 185)
		self.align_center(self.cn, pos)
	
	def getTimeZone(self,selindex=0):
		#self.selindex = selindex

		return self.timezone_name[selindex], self.timezone[selindex]

	def show(self):		
		ListStage.show(self)
		#self.selindex = 0
		#self.display_dst_icon
		
	def  handle_key(self, key,flag=False):
		if key == config.Menu1 or key == 'OK':
			def cb():
				import ntptime
				setting.set_ntptimezone(str(self.timezone[self.selindex]))
				ntptime.set_ntpadjust()
				setting.current_time = int(ntptime.ntime())
				setting.save()
				'''
				stage = runtime.manager.find_stage('idle')
				if stage:
					stage.update_calendar()
				'''
				#runtime.manager.change_stage_org(IdleStage, True)
				runtime.manager.back_stage()
			stage = NotifyStage(_('Timezone saved'), icon = None, duration=2000, cb=cb)
			runtime.manager.change_stage(stage)

		elif key == config.Menu4 or key == 'CLR':
			runtime.manager.back_stage()
		elif key == config.Red:
			runtime.manager.back_stage('idle')
		elif  key == 'Down' or key == 'Right':		
			self.selindex +=1
			print '### SELINDEX+ ', self.selindex, ' ', len(self.timezone_name)
			if self.selindex > len(self.timezone_name)-1:
				self.selindex = 0
			#self.display_dst_icon(self.selindex)
			self.update_line(self.selindex)
		elif  key == 'Up' or key == 'Left':
			self.selindex -= 1
			print '### SELINDEX- ', self.selindex, ' ', len(self.timezone_name)
			if self.selindex < 0:
				self.selindex = len(self.timezone_name)-1 
			#self.display_dst_icon(self.selindex)
			self.update_line(self.selindex)
		else:
			return False
		return True
		
	def destroy(self):
		ListStage.destroy(self)

		
class TimeDetailStage(ListTimeStage):
	title = _('CITY LIST')
	titleimage = uiconfig.worldtime_title, uiconfig.worldtime_title_pos
	def __init__(self, total_city_time = None,index = 0):	
		self._get_time = utils.Timer(3600,self.get_time1)
		self.choice = []
		i=0
		for i in range(40):
			str_city = total_city_time[i][0]         
			'''
			#if i in (1,4,11,13,15,39):
			if i in (1,12,5,30,10,16,29):
				str_city = str_city+'        '
				print '777777',len(str_city)
				
			#elif i in (2,3,7,29,38):
			elif i in (4,36,28,6):
				str_city = str_city+'    '
				print '99999',len(str_city)
			#elif i in (5,6,14,16,21,31,32,34):
			elif i == 8:
				str_city = str_city+'   '
			elif i in (7,2,11,15,0,13,31,18,35):
				str_city = str_city+'         '
				print '6666666',len(str_city)
			#elif i in (8,9,10,17,18,19,22,27,30):
			elif i in (3,30,17,25,14,26,39,9):
				str_city = str_city+'         '
				print'5555555',len(str_city)
			#elif i in (12,25,36):
			elif i in (38,21):
				str_city = str_city+'         '
				print'44444444',len(str_city)
			#elif i in (20,23,26,37):
			elif i in (24,37,32,23):
				str_city = str_city+'   '
				print'10000000',len(str_city)
			#elif i in (0,24):
			elif i in (33,34):
				str_city = str_city+'  '
				print'111111',str_city
			#elif i ==8:
			elif i ==27:
				str_city = str_city+'     '
				print'8888888',len(str_city)
			#elif i in (28,35):
			elif i in (19,22):
				str_city = str_city+''
			if i == 20:
				#str_city = str_city+'        '
				str_city = str_city+'          '
			space = '              '
			#self.info = self.info[:13]
			#self.info = self.info[30:]
			self.info = str_city[:13]+space[10:30]
			self.info1 = self.info [:30] +total_city_time[i][1]
			'''
			str_city2=total_city_time[i][1]
			self.info1 = str_city2[:23] +'  ' + str_city
			self.choice.append(self.info1)

		ListTimeStage.__init__(self, choice=self.choice,left='',right='')		
		#self.ui.set_focus(index)
		
	def activate(self,index):
		return
		
	def get_time1(self):
		self._get_time = utils.Timer(3600,self.get_time1)
		self.choice.append(self.info1)
		choice = self.choice
		
	def handle_key(self,key):
		 if key == config.Menu4 or key == 'CLR':
		 	stage = WorldTimeStage
		 	runtime.manager.change_stage(stage)
		 	return True
		 else:
			ret = ListTimeStage.handle_key(self,key)	
			return ret

		
class DSTEnableStage(ListStage):
	def __init__(self,index_city = 0):
		ListStage.__init__(self)
		self.check = 0
		self.index = 0
		self.dst_city_name = []
		self.index_city = index_city
		self.ui = baseui.DSTEnableUI(_('LIST'), '' , '' , _('BACK'))
		fp = open('worldtime_table.txt','r')
		self.city = fp.readline().split(',')[:-1]
		self.add_time = fp.readline().split(',')[:-1]
		self.dst_time_change = fp.readline().split(',')[:-1]
		fp.close()
		#1,3,6,11,13,14,15,16,18,23,30,31,34
		self.dst_city_name.append(self.city[1])
		self.dst_city_name.append(self.city[2])
		self.dst_city_name.append(self.city[9])
		self.dst_city_name.append(self.city[10])
		self.dst_city_name.append(self.city[11])
		self.dst_city_name.append(self.city[12])
		self.dst_city_name.append(self.city[13])
		self.dst_city_name.append(self.city[14])
		self.dst_city_name.append(self.city[15])
		self.dst_city_name.append(self.city[16])
		self.dst_city_name.append(self.city[18])
		self.dst_city_name.append(self.city[36])
		self.dst_city_name.append(self.city[37])
		
		self.dst_city_name[self.index_city]
		
		self.dst_disable = runtime.evas.text ( text= "Disable", pos=(172, 105), \
				color=uiconfig.worldtime_text_color, \
				font=uiconfig.worldtime_text_font)
		self.ui.add(self.dst_disable)

		self.dst_enable1 = runtime.evas.text ( text= "1 Hour", pos=(172, 147), \
				color=uiconfig.worldtime_text_color, \
				font=uiconfig.worldtime_text_font)
		self.ui.add(self.dst_enable1)
		
		self.dst_enable2 = runtime.evas.text ( text= "2 Hour", pos=(172, 189), \
				color=uiconfig.worldtime_text_color, \
				font=uiconfig.worldtime_text_font)
		self.ui.add(self.dst_enable2)
		
		pos = uiconfig.DST_select_image_pos
		size = uiconfig.DST_select_image_size
		self.select_img = utils.put_image(uiconfig.DST_select_image,pos)
		self.select_img.hide()
		self.ui.add(self.select_img)

		name = uiconfig.DST_checkbox_image
		pos = uiconfig.DST_checkbox_image_pos
		size = uiconfig.DST_checkbox_image_size
		self.checkbox1_img = utils.put_image(name,pos)
		self.checkbox1_img.hide()
		self.ui.add(self.checkbox1_img)

		self.checkbox2_img = utils.put_image(name,(139,147))
		self.checkbox2_img.hide()
		self.ui.add(self.checkbox2_img)

		self.checkbox3_img = utils.put_image(name,(139,189))
		self.checkbox3_img.hide()
		self.ui.add(self.checkbox3_img)

		#pos=(145, 70)
		pos =  240 - (len(self.dst_city_name[self.index_city])*10)/2, 70
		self.dst_ct = runtime.evas.text ( text= "%s" %(self.dst_city_name[self.index_city]), pos=pos, \
				color=uiconfig.worldtime_text_color, \
				font=uiconfig.worldtime_text_font)
		self.ui.add(self.dst_ct)
	
		if self.check == 0:
			name = uiconfig.image_dir + uiconfig.DST_checkbox_image
		else:
			name = uiconfig.image_dir + uiconfig.DST_checkbox_image_r
		
	def update_select1(self,index_city):
		self.select_img.file = uiconfig.image_dir + uiconfig.DST_select_image_r
		self.select_img.pos = uiconfig.DST_select_image_pos
		self.select_img.size = uiconfig.DST_select_image_size

	def update_city(self,index_city):
		self.dst_ct.text_set("%s"%self.dst_city_name[self.index_city])
		self.dst_ct.pos =  240 - (len(self.dst_city_name[self.index_city])*10)/2, 70
	
	def update_time(self,index_city,dst_time=1):
		i = 0
		s1 = ''
		s2=''
		s3=''
		if self.index_city == 0:		i = 1
		elif self.index_city == 1:	i = 2
		elif self.index_city == 2:	i = 9
		elif self.index_city == 3:	i= 10
		elif self.index_city == 4:	i = 11
		elif self.index_city == 5:	i = 12
		elif self.index_city == 6:	i = 13
		elif self.index_city == 7:	i = 14
		elif self.index_city == 8:	i = 15
		elif self.index_city == 9:	i = 16
		elif self.index_city == 10:	i = 18
		elif self.index_city == 11:	i = 36
		elif self.index_city == 12:	i = 37
		#self.dst_time_change[self.index_city] = dst_time
		self.dst_time_change[i] = dst_time
		for i in range(len(self.city)):
			s1 = s1+'%s,'%self.city[i]
			s1 = str(s1)
			print 'city=======',self.city
			s2 = s2+'%s,'%self.add_time[i]
			s2 = str(s2)
			print 'addtime=======',self.add_time
			s3 = s3+'%s,'%self.dst_time_change[i]
			s3 = str(s3)
			print 'dst_time=======',self.dst_time_change
		
		#1,3,6,11,13,14,15,16,18,23,30,31,34
		f = open('worldtime_table.txt','w')
		f.write(s1+'\n')
		f.write(s2 +'\n')
		f.write(s3+'\n')
		f.close()
		f = open('worldtime_table.txt','r')
		#print f.readline()
		#print f.readline()
		#print f.readline()
		f.close()
	
	def set_focus(self,index):
		if index == 0:
			self.ui.set_right('')
			self.select_img.show()
		if index == 1:
			self.select_img.file = uiconfig.image_dir +uiconfig.DST_select_image
			self.ui.set_right(_('SELECT'))
		if index == 2:
			self.ui.set_right(_('SELECT'))
		if index ==3:
			self.ui.set_right(_('SELECT'))
			
	def show(self):
		Stage.show(self)
		self.index = 0
		self.set_focus(0)
		
	def handle_key(self,key):
		if key == config.Menu4:
			runtime.manager.back_stage()
		elif key == config.Menu3:
			runtime.manager.stack_stage(TimeDetailStage)
		elif key == config.Red:
			runtime.manager.stack_stage(WorldTimeStage)
			self.set_focus(self.ind_city)
		elif key == config.Menu2:
			if self.index == 1:
				if self.check == 1:
					self.check = 0
					self.checkbox1_img.file = uiconfig.image_dir + uiconfig.DST_checkbox_image
				else :
					self.check == 1
					self.checkbox1_img.file = uiconfig.image_dir  + uiconfig.DST_checkbox_image_r
					self.checkbox2_img.file = uiconfig.image_dir + uiconfig.DST_checkbox_image
					self.checkbox3_img.file = uiconfig.image_dir + uiconfig.DST_checkbox_image
					self.update_time(self.index_city,0)
			elif self.index == 2:
				if self.check == 1:
					self.check == 0
					#self.checkbox2_img.file = uiconfig.image_dir + uiconfig.DST_checkbox_image
				else:
					self.check == 1
					self.checkbox1_img.file = uiconfig.image_dir + uiconfig.DST_checkbox_image
					self.checkbox2_img.file = uiconfig.image_dir  + uiconfig.DST_checkbox_image_r
					self.update_time(self.index_city,1)
			elif self.index == 3:
				if self.check == 1:
					self.check == 0
					self.checkbox1_img.file = uiconfig.image_dir + uiconfig.DST_checkbox_image
					self.checkbox3_img.file = uiconfig.image_dir + uiconfig.DST_checkbox_image
				else:
					self.check == 1
					self.checkbox3_img.file = uiconfig.image_dir  + uiconfig.DST_checkbox_image_r
					self.checkbox2_img.file = uiconfig.image_dir + uiconfig.DST_checkbox_image
					self.update_time(self.index_city,2)
			return True
		elif key == 'Left':
			self.index_city -= 1
			if self.index_city < 0:
				self.index_city = len(self.dst_city_name)-1    
			self.update_city(self.index_city)
			self.update_select1(self.index_city)
			return True
		elif key == 'Right':
			self.index_city += 1
			if self.index_city > len(self.dst_city_name)-1:
				self.index_city = 0	
			self.update_city(self.index_city)
			self.update_select1(self.index_city)
			return True
		elif key == 'Down':
			self.index = self.index + 1
			if self.index > 3:
				self.index = 0
			self.set_focus(self.index)
			return True
		elif key == 'Up':
			self.index = self.index - 1
			if self.index < 0:	
				self.index = 3
			self.set_focus(self.index)
			return True
		return True
		
		
class OrganiserStage(ListStage):
	titleimage = uiconfig.title_agenda
	icon = uiconfig.agenda_icon
	def __init__(self):
		self.title = _('ORGANIZER')
		self.choice = (_('Phonebook'), _('Calendar'))
	
		ListStage.__init__(self)
		

	def activate(self, index):
		if index == 0: #phonebook
			import phonebook
			stage = phonebook.get_phonebook_stage()
			runtime.manager.stack_stage(stage)
		elif index == 1: #calendar
			runtime.manager.stack_stage(CalendarStage)

#thang [20080428 - 1] Calendar hien thi stage 

class CalendarStage(Stage):
	def __init__(self):
		self.ui = baseui.CalendarUI(_('LIST'),_('ADD'),_('TODAY'),_('BACK'))

	def handle_key(self,key):
		if key == config.Menu1 or key == 'OK':
			self.ui.clear_events()
			stage = CalendarListStage
			runtime.manager.stack_stage(stage)
			return True
		elif key in ('Up','Down','Left','Right', '1', '3', '5', '7', '9', config.Menu3):
			self.ui.handle_key(key)
			return True
		elif key == config.Menu4 or key == 'CLR':
			runtime.manager.back_stage('service stage')
			return True
		elif key == config.Menu2:
			if calendardb.count() >= config.max_calendar_count:
				stage = NotifyStage(_('You can add no more'), icon = None)
				runtime.manager.stack_stage(stage)
			else:
				status.editing_calendar_index = -1
				date = self.ui.date[self.ui.focus + 1]			
				stage = AddCalendarStage(date = date)
				runtime.manager.stack_stage(stage)
			return True
		return False

class CalendarListStage(ListCalendarStage):	
	def __init__(self):
		self.calendardb_index,self.choice = self.get_calendarlist()
		ListCalendarStage.__init__(self, title=_('CALENDAR'), choice=self.choice,left=_('EDIT'),right=_('ADD'),menu3 = _('DELETE'))
		if len(self.calendardb_index) > 0:
			ListCalendarStage.set_current_pos(self, 0)
			status.editing_calendar_index = 0
	def activate(self,index):
		return	
	def show(self):
		def cb_empty():
			#stage = CalendarStage
			#runtime.manager.change_stage(stage)
			runtime.manager.back_stage()
			return			
		self.calendardb_indexes, self.choice = self.get_calendarlist()
		if len(self.choice) == 0:		
			utils.player.play_effect(config.SETTING_FAILED)
			runtime.manager.change_stage(NotifyStage(_('Calendar empty'),icon = None, cb = cb_empty))
		else:
			if ListCalendarStage.get_current_pos(self) >= len(self.calendardb_indexes) or \
			   ListCalendarStage.get_current_pos(self) == -1:
				ListCalendarStage.set_current_pos(self, len(self.calendardb_indexes)-1)
				status.editing_calendar_index = ListCalendarStage.get_current_pos(self)
			self.change_choice(self.choice)
			ListCalendarStage.show(self)
	def get_calendarlist(self):
		return range(calendardb.count()), calendardb.get_names()		
	def handle_key(self,key):
		if key == config.Menu4 or key == 'CLR':
			#stage = CalendarStage
			#runtime.manager.change_stage(stage)
			runtime.manager.back_stage()
			return
		ret = ListCalendarStage.handle_key(self,key)	
		if key in ('Up', 'Down'):
			status.editing_calendar_index = self.calendardb_indexes[self.ui.get_focus()]
			ListCalendarStage.set_current_pos(self, status.editing_calendar_index)
		elif key == config.Menu1 or key == 'OK':
			status.editing_calendar_index = self.calendardb_indexes[self.ui.get_focus()]
			ListCalendarStage.set_current_pos(self, status.editing_calendar_index)
			stage = AddCalendarStage
			runtime.manager.stack_stage(stage)
		elif	key == config.Menu2:
			if calendardb.count() >= config.max_calendar_count:
				stage = NotifyStage(_('You can add no more'), icon = None)
				runtime.manager.stack_stage(stage)
			else:
				status.editing_calendar_index = -1
				ListCalendarStage.set_current_pos(self, -1)
				stage = AddCalendarStage
				runtime.manager.stack_stage(stage)
			return True
		elif key == config.Menu3:
			self.delete_item()
		return ret
	def delete_item(self):
		def yes():
			# Delete This Item			
			calendardb.remove(status.editing_calendar_index)			
			if not calendardb.is_empty():	
				icon = uiconfig.calendar_agenda_icon
				utils.player.play_effect(config.SETTING_SUCCEEDED)
				stage = NotifyStage(_('Entry deleted'),icon = None)
				runtime.manager.change_stage(stage)			
			else:	
				def cb():
					icon = uiconfig.calendar_agenda_icon
					utils.player.play_effect(config.SETTING_FAILED)
					stage = NotifyStage(_('Calendar empty'),icon = None)
					runtime.manager.change_stage(stage)
				icon = uiconfig.calendar_agenda_icon
				utils.player.play_effect(config.SETTING_SUCCEEDED)
				#stage = NotifyStage(_('Entry deleted'),icon = None, cb=cb)
				stage = NotifyStage(_('Entry deleted'),icon = None)
				runtime.manager.change_stage(stage)			
			return		
		def no():
			runtime.manager.back_stage()
			return
		stage = YesNoStage(_('Delete this entry?'), yes, no, '', uiconfig.calendar_agenda_icon)
		runtime.manager.stack_stage(stage)	

#thang [20080428 - 1] ================= 

class DSTEnableStage(ListStage):
	def __init__(self,index_city = 0):
		ListStage.__init__(self)
		self.check = 0
		self.index = 0
		self.dst_city_name = []
		self.index_city = index_city
		self.ui = baseui.DSTEnableUI(_('LIST'), '' , '' , _('BACK'))
		fp = open('worldtime_table.txt','r')
		self.city = fp.readline().split(',')[:-1]
		self.add_time = fp.readline().split(',')[:-1]
		self.dst_time_change = fp.readline().split(',')[:-1]
		fp.close()
		#1,3,6,11,13,14,15,16,18,23,30,31,34
		self.dst_city_name.append(self.city[1])
		self.dst_city_name.append(self.city[2])
		self.dst_city_name.append(self.city[9])
		self.dst_city_name.append(self.city[10])
		self.dst_city_name.append(self.city[11])
		self.dst_city_name.append(self.city[12])
		self.dst_city_name.append(self.city[13])
		self.dst_city_name.append(self.city[14])
		self.dst_city_name.append(self.city[15])
		self.dst_city_name.append(self.city[16])
		self.dst_city_name.append(self.city[18])
		self.dst_city_name.append(self.city[36])
		self.dst_city_name.append(self.city[37])
		
		self.dst_city_name[self.index_city]
		
		self.dst_disable = runtime.evas.text ( text= "Disable", pos=(172, 105), \
				color=uiconfig.worldtime_text_color, \
				font=uiconfig.worldtime_text_font)
		self.ui.add(self.dst_disable)

		self.dst_enable1 = runtime.evas.text ( text= "1 Hour", pos=(172, 147), \
				color=uiconfig.worldtime_text_color, \
				font=uiconfig.worldtime_text_font)
		self.ui.add(self.dst_enable1)
		
		self.dst_enable2 = runtime.evas.text ( text= "2 Hour", pos=(172, 189), \
				color=uiconfig.worldtime_text_color, \
				font=uiconfig.worldtime_text_font)
		self.ui.add(self.dst_enable2)
		
		pos = uiconfig.DST_select_image_pos
		size = uiconfig.DST_select_image_size
		self.select_img = utils.put_image(uiconfig.DST_select_image,pos)
		self.select_img.hide()
		self.ui.add(self.select_img)

		name = uiconfig.DST_checkbox_image
		pos = uiconfig.DST_checkbox_image_pos
		size = uiconfig.DST_checkbox_image_size
		self.checkbox1_img = utils.put_image(name,pos)
		self.checkbox1_img.hide()
		self.ui.add(self.checkbox1_img)

		self.checkbox2_img = utils.put_image(name,(139,147))
		self.checkbox2_img.hide()
		self.ui.add(self.checkbox2_img)

		self.checkbox3_img = utils.put_image(name,(139,189))
		self.checkbox3_img.hide()
		self.ui.add(self.checkbox3_img)

		#pos=(145, 70)
		pos =  240 - (len(self.dst_city_name[self.index_city])*10)/2, 70
		self.dst_ct = runtime.evas.text ( text= "%s" %(self.dst_city_name[self.index_city]), pos=pos, \
				color=uiconfig.worldtime_text_color, \
				font=uiconfig.worldtime_text_font)
		self.ui.add(self.dst_ct)
	
		if self.check == 0:
			name = uiconfig.image_dir + uiconfig.DST_checkbox_image
		else:
			import alarm
			runtime.manager.change_stage(alarm.NoAgendaStage)
			return
		ListStage.show(self)

	def activate(self, index):
		import alarm
		stage = alarm.get_stage(index)
		runtime.manager.stack_stage(stage)

class AddCalendarStage(Stage): # ListStage
	def __init__(self,left=_('SAVE'), right='', menu3=_('KOR'), menu4=_('BACK'), date=None, unselbarpos=[]):		
		self.choose_ctl = 0
		if status.editing_calendar_index == -1:
			status.calendar_item = calendardb.new_item()
			if date != None:
				status.calendar_item[1] = date[2]
				status.calendar_item[2] = date[1]
				status.calendar_item[3] = date[0]
			status.calendar_item[0] = str(calendardb.count())
		else:
			status.calendar_item = calendardb.get_item(status.editing_calendar_index)	
			status.calendar_item[0] = str(status.editing_calendar_index)

		# shchun : global automata change		
		if setting.lang == 'Korean':
			menu3=_('KOR')
		else:
			menu3=_('abc')
		# end shchun
		self.ui = baseui.AddCalendarUI(left, right, '', menu3, menu4)		
		#self.ui.set_fixed_automata(self.ui.ctl_memo,None, False)	

		# shchun : global automata change
		if setting.lang == 'Korean':
			self.ui.set_automata(self.ui.ctl_memo,'hangul', False)
		else:
			self.ui.set_automata(self.ui.ctl_memo,'multitap', 'lower')
		# end shchun
		#self.ui.automata = 'hangul',0	

		self.symbol_stage_timer = None

	def destroy(self):
		Stage.destroy(self)
		self.symbol_stage_timer = None
		
	def set_right(self,right):	
		self.right = right
		runtime.rb.set_text(self.right)

	def insert_symbol(self, s):
		def back_to_symbol():
			from basemodel import SymbolSelectionStage
			runtime.manager.stack_stage(SymbolSelectionStage(self, True))
			self.symbol_stage_timer = None
			
		before_text = self.ui.get_text()
		self.ui.insert_text(s)
		after_text = self.ui.get_text()

		if before_text == after_text:
			runtime.manager.change_stage(NotifyStage(_('Max length exceeded'), uiconfig.baloon_message_icon))
		else:
			runtime.manager.back_stage()
			#self.symbol_stage_timer = utils.Timer(uiconfig.back_to_symbol_timeout, back_to_symbol)
			

	
	def set_menu3(self):
		if self.ui.automata[0] == '123':		menu3 = '123'
		elif self.ui.automata[0] == 'hangul':	menu3 = _('KOR')
		elif self.ui.automata[0] == 'multitap' and self.ui.automata[1] == 'lower':			menu3 = _('abc')
		elif self.ui.automata[0] == 'multitap' and self.ui.automata[1] == 'upper':			menu3 = _('ABC')
		elif self.ui.automata[0] == 'multitap' and self.ui.automata[1] == 'first capital':	menu3 = _('Abc')
		elif self.ui.automata[0] == 't9' and self.ui.automata[1] == 'lower':			menu3 = _('T9abc')
		elif self.ui.automata[0] == 't9' and self.ui.automata[1] == 'upper':			menu3 = _('T9ABC')
		elif self.ui.automata[0] == 't9' and self.ui.automata[1] == 'first capital':	menu3 = _('T9Abc')
		else:							menu3 = _('SYMBOL')
		runtime.menu3.set_text(menu3)
		
		if menu3 ==_('SYMBOL'):
			# shchun : global automata change
			self.ui.set_automata(self.ui.ctl_memo, 'multitap', 'lower')
			if setting.lang == 'Korean':
				self.ui.set_automata(self.ui.ctl_memo,'hangul', False)
			else:
				self.ui.set_automata(self.ui.ctl_memo,'multitap', 'lower')	
			
			from basemodel import SymbolSelectionStage
			runtime.manager.stack_stage(SymbolSelectionStage(self, True))
			# end shchun

			#self.ui.set_fixed_automata(self.ui.ctl_memo, None, False)	
			#from basemodel import SymbolSelectionStage
			#runtime.manager.stack_stage(SymbolSelectionStage(self, True))

	def show(self):
		self.ui.show()
		if self.choose_ctl == 0:	
			self.ui.ctl_memo.lostFocus()
			#self.ui.ctl_yearly.lostFocus()
			#self.ui.ctl_holiday.lostFocus()
			self.ui.ctl_date.showFocus()
			runtime.menu3.set_text('')
		else:
			self.ui.ctl_date.lostFocus()
			if self.ui.ctl_memo.length() > 0:
				self.set_right(_('CLEAR'))
			else:
				self.set_right('')
			self.ui.ctl_memo.showFocus()
			self.set_menu3()

	def save(self):
		#index,day, month, year, yearly, holiday, memo		
		year,month,day = self.ui.ctl_date.date
		status.calendar_item[1] = str(day)		
		status.calendar_item[2] = str(month)		
		status.calendar_item[3] = str(year)
		status.calendar_item[4] = '0' # str(self.ui.ctl_yearly.value)
		status.calendar_item[5] = '0' # str(self.ui.ctl_holiday.value)
		status.calendar_item[6] = str(self.ui.ctl_memo.get_text())
		item = status.calendar_item
		if status.editing_calendar_index != -1:
			calendardb.remove(status.editing_calendar_index)			
		calendardb.insert_item(item)		
		#status.editing_calendar_index = -1
		status.calendar_item = None	
		
	def handle_key(self,key):
		if key == config.Menu1 or key == 'OK':			
			memo = self.ui.ctl_memo.get_text()
			if memo == '':
				utils.player.play_effect(config.SETTING_FAILED)
				stage = CalendarNotifyStage( _('Memo insert !'))
				runtime.manager.stack_stage(stage)				
				return True
			self.save()
			def cb_save_ok():
				#stage = CalendarStage
				#runtime.manager.change_stage(stage)
				runtime.manager.back_stage()
				return
			utils.player.play_effect(config.SETTING_SUCCEEDED)
			stage = CalendarNotifyStage(_('Set is saved'), cb=cb_save_ok)
			runtime.manager.change_stage(stage)			
			return True			
		elif key == config.Menu2:
			if  self.choose_ctl == 1:
				self.ui.ctl_memo.handle_key('\b')
				if self.ui.ctl_memo.length() == 0:
					self.set_right('')
				return True
#			elif  self.choose_ctl == 1:
#				self.ui.ctl_yearly.handle_key(key)
#				if self.ui.ctl_yearly.value == 0:
#					self.set_right(_('SELECT'))
#				else:
#					self.set_right(_('DESELECT'))
#				return True
#			elif  self.choose_ctl == 2:
#				self.ui.ctl_holiday.handle_key(key)
#				if self.ui.ctl_holiday.value == 0:
#					self.set_right(_('SELECT'))
#				else:
#					self.set_right(_('DESELECT'))
#				return True
			return True
		elif key == config.Menu3:
			if self.choose_ctl == 1:				
				self.ui.automata_idx = utils.get_automata_idx(*self.ui.automata)
				if setting.lang == 'Korean':
					self.ui.automata_idx = (self.ui.automata_idx + 1) % len(config.automata_list_hangul)
					self.ui.automata = config.automata_list_hangul[self.ui.automata_idx]		
				else:	
					self.ui.automata_idx = (self.ui.automata_idx + 1) % len(config.automata_list)	
					self.ui.automata = config.automata_list[self.ui.automata_idx]	
				self.ui.set_automata(self.ui.ctl_memo,*self.ui.automata)
				self.set_menu3()			
			return True		
		elif key == config.Menu4:
			runtime.manager.back_stage()
			return True
		elif key == 'CLR':
			if self.choose_ctl == 1:
				if self.ui.ctl_memo.length() == 0:
					runtime.manager.back_stage()
				else:
					self.ui.ctl_memo.handle_key('\b')
					if self.ui.ctl_memo.length() == 0:
						self.set_right('')
			else:
				self.ui.ctl_date.handle_key('Left')
				#runtime.manager.back_stage()
		elif key == config.Red:
			runtime.manager.back_stage('idle')
		elif key == 'Up':
			self.choose_ctl = 1 - self.choose_ctl
# 			self.choose_ctl -= 1
#			if self.choose_ctl <0: self.choose_ctl = 1
			self.ui.ctl_date.lostFocus()
#			self.ui.ctl_yearly.lostFocus()
#			self.ui.ctl_holiday.lostFocus()
			self.ui.ctl_memo.lostFocus()					
			if self.choose_ctl == 0:
				self.set_right('')
				self.ui.ctl_date.showFocus()
				runtime.menu3.set_text('')
			elif self.choose_ctl == 1:
#				self.ui.ctl_yearly.handle_key(key)				
#				if self.ui.ctl_yearly.value == 0:
#					self.set_right(_('SELECT'))
#				elif self.ui.ctl_yearly.value == 1:
#					self.set_right(_('DESELECT'))
#				else:
#					self.set_right(_('SELECT'))
#				self.ui.ctl_yearly.showFocus()
#			elif self.choose_ctl == 2:
#				self.ui.ctl_holiday.handle_key(key)
#				if self.ui.ctl_holiday.value == 0:
#					self.set_right(_('SELECT'))
#				elif self.ui.ctl_holiday.value == 1:
#					self.set_right(_('DESELECT'))
#				else:
#					self.set_right(_('SELECT'))
#				self.ui.ctl_holiday.showFocus()
#			elif self.choose_ctl == 3:
			 	if self.ui.ctl_memo.length() > 0:
					self.set_right(_('CLEAR'))
				else:
					self.set_right('')
				self.ui.ctl_memo.showFocus()
				self.set_menu3()
			return True
		elif key == 'Down':
			self.choose_ctl = 1 - self.choose_ctl
#			self.choose_ctl += 1
#			if self.choose_ctl > 3: self.choose_ctl = 0
			self.ui.ctl_date.lostFocus()
#			self.ui.ctl_yearly.lostFocus()
#			self.ui.ctl_holiday.lostFocus()
			self.ui.ctl_memo.lostFocus()					
			if self.choose_ctl == 0:
				self.set_right('')
				self.ui.ctl_date.showFocus()
				runtime.menu3.set_text('')
			elif self.choose_ctl == 1:				
#				if self.ui.ctl_yearly.value == 0:
#					self.set_right(_('SELECT'))
#				elif self.ui.ctl_yearly.value == 1:
#					self.set_right(_('DESELECT'))
#				else:
#					self.set_right(_('SELECT'))
#				self.ui.ctl_yearly.showFocus()
#			elif self.choose_ctl == 2:
#				
#				if self.ui.ctl_holiday.value == 0:
#					self.set_right(_('SELECT'))
#				elif self.ui.ctl_holiday.value == 1:
#					self.set_right(_('DESELECT'))
#				else:
#					self.set_right(_('SELECT'))
#				self.ui.ctl_holiday.showFocus()
#			elif self.choose_ctl == 3:
				if self.ui.ctl_memo.length() > 0:
					self.set_right(_('CLEAR'))
				else:
					self.set_right('')
				self.ui.ctl_memo.showFocus()
				self.set_menu3()
			return True
		elif key in ('Left', 'Right'):
			if self.choose_ctl == 0:
				self.ui.ctl_date.handle_key(key)
			elif self.choose_ctl == 1:#3:
				self.ui.ctl_memo.handle_key(key)
			return True
		else:
			if self.choose_ctl == 0:
				self.ui.ctl_date.handle_key(key)
			elif self.choose_ctl == 1:
#				self.ui.ctl_yearly.handle_key(key)
#			elif self.choose_ctl == 2:
#				self.ui.ctl_holiday.handle_key(key)	
#			elif self.choose_ctl == 3:
				self.ui.ctl_memo.handle_key(key)
				if self.ui.ctl_memo.length() > 0:
					self.set_right(_('CLEAR'))
				else:
					self.set_right('')
			return True
		return False

#	def is_valid_date():
#		year, month, day = self.ui.ctl_date.date
#		if year % 100==0 and year%400!=0:
#			if month in (2,4,6,9,11):
#				if day > 29:
#					return False
#			elif month in (1,3,5,7,8,10,12):
#				if day > 31:
#					return False
#		else
#			if month in (2,4,6,9,11):
#				if day > 28:
#					return False
#			elif month in (1,3,5,7,8,10,12):
#				if day > 31:
#					return False
#		
#		return True
		
class VideoSettingStage(ListStage):
	icon = uiconfig.video_setting_icon
	name = 'videosettingstage'

	def __init__(self):
		self.title = _('VIDEO SETTINGS')
		self.choice_pstn = _('Video Size'), _('Video Quality'), _('PCM upstream')
		self.choice_ip = _('Video Size'), _('Video Quality')

		import profile
		if profile.ip_mode == 0: #pstn
			self.choice = self.choice_pstn
		else:
			self.choice = self.choice_ip
		ListStage.__init__(self, choice=self.choice)

	def activate(self, index):
		import videosetting
		stage = videosetting.get_stage(index)
		runtime.manager.stack_stage(stage)

# KA: [20080218] Volume
#class AudioSettingStage(ListStage): 
class SoundStage(ListStage):

	name = 'audio setting'
	icon = uiconfig.setting_audio_icon
	#titleimage = uiconfig.title_sound
	def __init__(self):
		self.title = _('SOUND')
		self.choice = _('Select bell'), _('Select effect'), _('Volume setting'), _('Group bell setting'), _('WOW HD setting')

		ListStage.__init__(self, self.choice, self.title, self.icon)
		#status.supervision_not_allowed = 1
		
	def activate(self, index):
		if index == 0:
			#stage = SelectBellStage : Newair7 20080515
			import sounds
			stage = sounds.NewSelectBellStage 
#		elif index == 1:
#			if (status.get_regstatus_mmi() == 0) and (config.myann_test_flag == False):
#				stage = NotifyStage(_('Please use after register to server'), icon = uiconfig.video_call_connect_icon)
#				runtime.manager.stack_stage(stage)
#				return
#				
#			cur_profile=profile.profile.get_profile()
#			if (cur_profile == 1 and not runtime.peek_lanlink()) or \
#						(cur_profile == 2 and not runtime.peek_wifilink()):	
#				msg = _('Check network connection.')
#				stage = NotifyStage(msg, icon = uiconfig.video_call_connect_icon)
#				runtime.manager.stack_stage(stage)
#				return True
#				
#			if runtime.myannapp:
#				import myannapp
#				if not runtime.myannapp.is_running():
#					runtime.manager.stack_stage(myannapp.MyAnnStage(config.BELL_DOWNLOAD_URL))
#					from eaHandler import EaHandler
#					runtime.eaHandler.activateApplication_browser(destination=EaHandler.BROWSER)
#			return
		elif index == 1:
			#stage = SelectEffectStage : Newair7 20080515
			import sounds
			stage = sounds.NewSelectEffectStage
		elif index == 2:
			stage = VolumeSettingStage
		elif index == 3:
			#import phonebook
			#stage = phonebook.GroupStage
			import sounds
			stage = sounds.GroupBellStage
		elif index == 4:
			import sounds
			stage = sounds.SRSWOWSettingStage
		else:
			return
		runtime.manager.stack_stage(stage)
	
	def destroy(self):
		status.supervision_not_allowed = 0
		ListStage.destroy(self)


class SelectBellStage(ListStage):

	def __init__(self):
		self.title = _('SELECT BELL')
		self.choice = _('Basic bell'), _('Sweet bell'), _('Merry bell'), _('Classic bell'), _('Effect bell')	
		ListStage.__init__(self)
		
	def activate(self, index):
		import sounds
		stage = sounds.AudioGalleryStage('ring')
		runtime.manager.stack_stage(stage)
		return

class SelectEffectStage(ListStage):
	def __init__(self):
		self.title = _('SELECT EFFECT')
		self.choice = _('Button sound'), _('Setting sound'), ('Message sound'), ('Weather sound')
		ListStage.__init__(self)

	def activate (self, index):
		return

class VolumeSettingStage(ListStage):
	name = 'audio setting'
	icon = uiconfig.setting_audio_volume_icon
	#titleimage= uiconfig.title_setting_audio_volume

	def __init__(self):
		self.title = _('VOLUME SETTING')
		self.choice = _('Bell volume'), _('Handset volume'),  _('Speaker volume'), _('Stereo volume'), _('Keytone volume'), _('Effect volume'), _('Alarm volume')
		ListStage.__init__(self, self.choice, self.title, self.icon)
		#status.supervision_not_allowed = 1

	def activate(self, index):

		print 'SELF.CHOICE[INDEX] ==', self.choice[index],  _('Bell volume')
		if self.choice[index] == _('Bell volume'):
			print 'It worked'
			import ringer
			stage = ringer.VolumeStage
		elif self.choice[index] == _('Handset volume'):
			stage = phonesetting.HandsetVolumeStage
		elif self.choice[index] == _('Speaker volume'):
			stage = phonesetting.SpeakerVolumeStage
		elif self.choice[index] == _('Stereo volume'):
			stage = phonesetting.StereoVolumeStage
		elif self.choice[index] == _('Keytone volume'):
			stage = phonesetting.KeytoneVolumeStage
		elif self.choice[index] == _('Effect volume'):
			stage = phonesetting.EffectVolumeStage
		elif self.choice[index] == _('Alarm volume'):
			stage = phonesetting.AlarmVolumeStage
		else:
			print 'It passed here'
			return
		runtime.manager.stack_stage(stage)

	def destroy(self):
		status.supervision_not_allowed = 0
		ListStage.destroy(self)


class VoIPSettingNotifyStage(NotifyStage):
	domonitor_forbidden = True
	def __init__(self, message,cb=None):
#Roxia Begin smyook 06.03.03 auto configuration
		#status.critical_entered = True
#Roxia End smyook
		icon = uiconfig.baloon_setting_voip_icon
		NotifyStage.__init__(self, message, icon, cb)

class VoIPEditor(Stage):
	domonitor_forbidden = True
	def __init__(self, title, subtitle, cb, text=None, ischr=False, textmax=-1, isauto=False, only_num = -1, need_hangul=True):
		self.p_subtitle = subtitle
		self.cb = cb
		self.ischr = ischr
		self.isauto = isauto
		self.flag = only_num
		self.need_hangul = need_hangul

		#if not need_hangul:
		#	self.ui = baseui.EntryNoHangulUI( '', '', title,  subtitle, '', '', _('BACK'))
		#else:
		if self.isauto:
			self.ui = baseui.EntryUI( '', '', title,  subtitle, '', '', _('BACK'), need_hangul=self.need_hangul)
		else:
			self.ui = baseui.EntryUI( _('OK'), '', title,  subtitle, '', '',  _('BACK'), need_hangul=self.need_hangul)

		# vpark 2007.08.28	
		subtitle_index = [_('Domain name'), _('Telephone num.'), _('Display name'), _('Auth. pwd'), _('Proxy address')]	
		automata = (None, False), ('123', False), (None, False), ('123', False), ('123', False)

		if subtitle == _('Domain name'):
			self.flag = 1
			self.ui.set_fixed_automata(None, False)
		elif subtitle == _('Telephone num.'):
			self.ui.entry.ascii_mode_case0 = True
			self.ui.set_fixed_automata('123', False)
		# hcryoo : [20071120_2] : 인증 이름의 default 입력 방식 수정 ㄱㄴㄷ --> 123
		elif subtitle == _('Display name'):
			self.ui.entry.ascii_mode_case1 = True
			self.ui.set_fixed_automata(None, False)
		elif subtitle == _('Auth. pwd') or subtitle == _('Auth. name'):
			self.ui.entry.ascii_mode_case1 = True
			self.ui.set_fixed_automata('123', False)
		# hcryoo : [20071120_2] : 인증 이름의 default 입력 방식 수정 ㄱㄴㄷ --> 123==
		elif subtitle == _('Proxy address'):	
			self.ui.entry.ascii_mode_case1 = True
			self.ui.set_fixed_automata('123', False)
		elif subtitle == _('Sms Server address'):	
			self.ui.entry.ascii_mode_case1 = True
			self.ui.set_fixed_automata('123', False)
		elif subtitle == _('manual download address'):
			self.ui.entry.ascii_mode_case1 = True
			self.ui.set_fixed_automata('123', False)
		elif subtitle == _('CTBW (80~800)') or subtitle == _('Bitrate (0~1000000)'):
			self.ui.entry.ascii_mode_case1 = True
			self.ui.set_fixed_automata('123', False)			
		else:
			if self.flag == 2:
				self.ui.set_fixed_automata('123', False)			
		
			else:
				self.ui.set_fixed_automata(None, False)

		if textmax != -1:
			self.ui.set_max(textmax)
		if text:
			self.ui.set_text(text)

	def show(self):
		if self.p_subtitle == _('Auth. pwd'):
			status.password_style = True
		Stage.show(self)

	def hide(self):
		if self.p_subtitle == _('Auth. pwd'):
			status.password_style = False
		Stage.hide(self)

	def destroy(self):
		if self.p_subtitle == _('Auth. pwd'):
			status.password_style = False
		Stage.destroy(self)

	def t9_add_word(self, word):
		self.ui.entry.t9_add_word(word)
		self.ui.update_entry_info()

	def activate_menu1(self):
		self.cb(self.ui)

	def insert_symbol(self, s):
		before_text = self.ui.get_text()
		self.ui.insert_text(s)
		after_text = self.ui.get_text()
		if before_text == after_text:
			runtime.manager.change_stage(NotifyStage(_('Max length exceeded'), uiconfig.baloon_message_icon))
		else:
			runtime.manager.back_stage()

	def handle_key(self, key):
		if key == config.Menu1 or key == 'OK':	#options Menu(left key)
			if self.ui.is_t9_add_word_mode():
				runtime.manager.stack_stage(T9AddWordStage(self))
				return True

			self.ui.reset_automata()
			self.activate_menu1()
		#elif key == config.Menu2:
		#	if self.ui.handle_key(key):
		#		if self.isauto and len(self.ui.get_text()) == 0:
		#			self.ui.def_left = ''
		#			self.ui.set_left('')
		#		return True
		#	runtime.manager.back_stage()

#		elif key in '#*' and self.flag == 2: 숫자만 입력해야 하는 경우
		elif key in ('#', '*', config.Menu3) and self.flag ==2:
			return True

		#proxy address
		elif key == '*':# and self.flag == 0:
			self.ui.insert_text('.')
		elif key == '#' and self.flag == 0:
			return True
		
		elif key == config.Menu3:
			if self.flag == 0:
				self.ui.set_automata('multitap', 'lower')
				self.flag = 1
			elif self.flag == 1:
				self.ui.set_automata('123', False)
				self.flag = 0
			else:
				# KA: [20070831] hangul lvp-2000
				# vpark 2006.08.28 automata	
				
				#if setting.lang == 'Korean':			
				if self.need_hangul:
					self.ui.automata_idx = utils.get_automata_idx(*self.ui.automata)
					self.ui.automata_idx = (self.ui.automata_idx + 1) % len(config.automata_list_hangul)	
					self.ui.automata = config.automata_list_hangul[self.ui.automata_idx]			
				else:			
					
					self.ui.automata_idx = utils.get_automata_idx_no_hangul(*self.ui.automata)
					self.ui.automata_idx = (self.ui.automata_idx + 1) % len(config.automata_list_mult_num_symbol)	
					self.ui.automata = config.automata_list_mult_num_symbol[self.ui.automata_idx]	
				print 'SET_AUTOMATA', self.ui.automata
				self.ui.set_automata(*self.ui.automata)		
				return True	
				# KA: [20070831] hangul lvp-2000 ==

		else:
			result = self.ui.handle_key(key)
			if self.isauto and key in '0123456789' and self.ui.get_text():
				self.ui.def_left = _('OK')
				self.ui.set_left(_('OK'))
			return result
		return True

class BasicEditor(Stage):
	def __init__(self, title, subtitle, cb, text=None, ischr=False, textmax=-1, isauto=False, only_num = -1):
		self.p_subtitle = subtitle
		self.cb = cb
		self.ischr = ischr
		self.isauto = isauto
		self.flag = only_num

		self.ui = baseui.EntryUI( _('OK'), _('BACK'), title,  subtitle)

		self.ui.entry.ascii_mode_case0 = True
		self.ui.set_fixed_automata('123', False)

		if textmax != -1:
			self.ui.set_max(textmax)
		if text:
			self.ui.set_text(text)

	def t9_add_word(self, word):
		self.ui.entry.t9_add_word(word)
		self.ui.update_entry_info()

	def activate_menu1(self):
		self.cb(self.ui)

	def insert_symbol(self, s):
		before_text = self.ui.get_text()
		self.ui.insert_text(s)
		after_text = self.ui.get_text()
		if before_text == after_text:
			runtime.manager.change_stage(NotifyStage(_('Max length exceeded'), uiconfig.baloon_message_icon))
		else:
			runtime.manager.back_stage()

	def handle_key(self, key):
		if key == config.Menu1:	#options Menu(left key)
			if self.ui.is_t9_add_word_mode():
				runtime.manager.stack_stage(T9AddWordStage(self))
				return True

			self.ui.reset_automata()
			self.activate_menu1()
		elif key == config.Menu2:
			if self.ui.handle_key(key):
				if self.isauto and len(self.ui.get_text()) == 0:
					self.ui.def_left = ''
					self.ui.set_left('')
				return True
			runtime.manager.back_stage()

		elif key in ('#', '*', 'SOFT3', 'SOFT4') and self.flag ==2:
			return True
		elif key == '*' and self.flag == 0:
			self.ui.insert_text('.')
		elif key == '#' and self.flag == 0:
			return True		
		elif key == 'SOFT4':
			if self.flag == 0:
				self.ui.set_automata('multitap', 'lower')
				self.flag = 1
			elif self.flag == 1:
				self.ui.set_automata('123', False)
				self.flag = 0
			else:
				self.ui.automata_idx = utils.get_automata_idx(*self.ui.automata)
				if setting.lang == 'Korean':			
					self.ui.automata_idx = (self.ui.automata_idx + 1) % len(config.automata_list_hangul)	
					self.ui.automata = config.automata_list_hangul[self.ui.automata_idx]			
				else:			
					self.ui.automata_idx = (self.ui.automata_idx + 1) % len(config.automata_list)	
					self.ui.automata = config.automata_list[self.ui.automata_idx]					
				self.ui.set_automata(*self.ui.automata)		
				return True	
		else:
			result = self.ui.handle_key(key)
			if self.isauto and key in '0123456789' and self.ui.get_text():
				self.ui.def_left = _('OK')
				self.ui.set_left(_('OK'))
			return result
		return True

class VoIPSettingStage(ListStage):
	
	icon = uiconfig.setting_voip_icon
	name = 'voip setting'

	def __init__(self):
		self.title = _('VoIP SETTINGS')
		self.choice_test = (_('User Information'), _('Proxy'), _('Registration'), _('Misc.'), _('DTMF')+' '+_('set'), _('Subscription'))
		self.choice_normal = (_('User Information'), _('Registration'), _('Misc.'))
		self.choice_PSTN = (_('Domain name'), )

		vdci_setting.load()
		#ka...hidden menu 2006.10.25
		import profile
		if status.debug_mode and profile.ip_mode == 0: #PSTN
			self.choice = self.choice_PSTN
		elif status.debug_mode:
			self.choice = self.choice_test
		else:
			self.choice = self.choice_normal
		ListStage.__init__(self, self.choice, self.title, self.icon)

		status.save_callback_other = self.auto_deregister_callback

	def destroy(self):
		status.save_callback_other = None
		ListStage.destroy(self)

	def auto_deregister_callback(self):
		import profile
		if profile.ip_mode == 1 and status.voip_setting_changed == True:
			roxia_trace('** auto_deregister_callback **')
			return (_('Please register to activate new setting'), uiconfig.baloon_setting_voip_icon)
		else:
			return None, None

	def activate(self, index):
		if self.choice[index] == _('User Information'):
			stage = UserInfomation()
		elif self.choice[index] == _('Proxy'):
			stage = Proxy()
		elif self.choice[index] == _('Registration'):
			stage = RegistrationStage()
		elif self.choice[index] == _('Misc.'):
			stage = Misc()
		#ka...hidden menu 2006.10.25
		elif self.choice[index] == _('Domain name'):
			pstn_domain = vdci_setting.pstn_domain
			stage = VoIPEditor(_('DOMAIN NAME'), _('Domain name'), self.domain_cb, text=pstn_domain, textmax = 50, ischr=True)
		elif self.choice[index] == _('Subscription'):
			stage = SubscriberSetStage()
		# KA: [20071206] KT DTMF nego
		else:
			stage = DTMFSetStage()
		# KA: [20071206] KT DTMF nego==
		runtime.manager.stack_stage(stage)

	#ka...hidden menu 2006.11.02
	def domain_cb(self, ui):
		text = ui.get_text()
		if len(text) == 0:
			runtime.manager.stack_stage(VoIPSettingNotifyStage(_('No text inserted.')))
		else:
			check_voip_change(vdci_setting.pstn_domain, text)
			vdci_setting.set_pstn_domain(text)
			runtime.manager.change_stage(VoIPSettingNotifyStage(_('Domain name set')))
			
	def handle_key(self, key):
		# check setting value
		import profile
		if profile.ip_mode == 1 and status.voip_setting_changed == True:
			if key in (config.Menu2, config.Red):
				phonesetting.do_autoderegister()
				return True

		return ListStage.handle_key(self, key)

	def no_cb(self):
		runtime.manager.back_stage()

	def disabled_cb(self):
		runtime.manager.change_stage(VoIPSettingNotifyStage(_('Auto provisioning disabled!')))

	def autopro_cb(self, ui):
		text = ui.get_text()
		if len(text) == 0:
			runtime.manager.stack_stage(VoIPSettingNotifyStage(_('No text inserted.')))
		else:
			runtime.manager.change_stage(VoIPSettingNotifyStage(_('Auto provisioning enabled!')))

	def vmsserver_cb(self, ui):
		text = ui.get_text()
		if len(text) == 0:
			runtime.manager.stack_stage(VoIPSettingNotifyStage(_('No text inserted.')))
		else:
			check_voip_change(vdci_setting.vms_server, text)

			vdci_setting.set_vms_server(text)
			runtime.manager.change_stage(VoIPSettingNotifyStage(_('VMS server address set')))

def check_voip_change(cur_value, new_value):
	if status.voip_setting_changed == False and cur_value != new_value:
		status.voip_setting_changed = True

# KA: [20071206] KT DTMF nego
class DTMFSetStage(ListStage):
	name = 'DTMFSet'
	
	icon = uiconfig.setting_voip_icon
	def __init__(self):
		self.title = _('DTMF SETTING')
		self.choice = (_('Inband'), _('Out of band'))

		ListStage.__init__(self, self.choice, self.title, self.icon)
		dtmf_set = setting.dtmf_set
		self.ui.set_focus(int(dtmf_set))

	def activate(self, index):
		if index == 0: # nego
			message = _('DTMF In-Band enable')
			setting.set_dtmf('0')
		else:
			message = _('DMTF Out-Band enable')
			setting.set_dtmf('1')
		stage = VoIPSettingNotifyStage(message)
		runtime.manager.change_stage(stage)
# KA: [20071206] KT DTMF nego==

class UserInfomation(Stage):
	title =  _('VoIP setting')
	choice = _('International call'), '060'
	domonitor_forbidden = True
	name = 'user information'
	
	def __init__(self):
		status.RichTextFocus = 0
		enabled = False
		self.flag = -1
		self.edit_entry_n=13
		
		self.ui = baseui.UserInfomationUI(_('SAVE'), '', self.title, '', _('BACK'), arg_enabled=enabled)
		#for i in range(edit_entry_n):
			#self.ui.set_fixed_automata(self.ui.list.entrys[i+1], '123', False)
			#self.ui.set_fixed_automata(self.ui.list.entrys[i], '123', False)
		
		#self.ui.automata = '123',0	
		#self.ui.show_bg = True

		self.EditedText=[]
		self.EditedText.append(vdci_setting.tel_num)
		#if vdci_setting.auth_name == '' and vdci_setting.tel_num != '':
		#	vdci_setting.auth_name = 	vdci_setting.tel_num + '@' + vdci_setting.domain			

		self.EditedText.append(vdci_setting.auth_name)
		if config.mmi_debug: 
			print '## status.voip_auth_pwd_type =', status.voip_auth_pwd_type
			print '## vdci_setting.auth_pwd=', vdci_setting.auth_pwd	
		
		if vdci_setting.auth_pwd.find('HASH:') >= 0:
			status.voip_auth_pwd_type = 1
			self.EditedText.append(vdci_setting.auth_pwd[5:])
			self.original_hexa_type_auth_pwd_value = vdci_setting.auth_pwd[5:]
			if config.mmi_debug: 
				print 'vdci_setting.auth_pwd[5:]=', vdci_setting.auth_pwd[5:]
		else:
			status.voip_auth_pwd_type = 0
			self.EditedText.append(vdci_setting.auth_pwd)
			self.original_hexa_type_auth_pwd_value = ''
			
		self.EditedText.append(vdci_setting.sip_uri)
		self.EditedText.append(vdci_setting.domain)
		self.EditedText.append(vdci_setting.proxy_addr)
		self.EditedText.append(vdci_setting.proxy_port)
		self.EditedText.append(vdci_setting.backup_proxy_addr)
		self.EditedText.append(vdci_setting.backup_proxy_port)
		self.EditedText.append(vdci_setting.primary_sbc_addr)
		self.EditedText.append(vdci_setting.primary_sbc_port)
		self.EditedText.append(vdci_setting.secondary_sbc_addr)
		self.EditedText.append(vdci_setting.secondary_sbc_port)
		ii = 0
		for item in self.EditedText:
			self.ui.txt_nums[ii].set_text(item)
			ii +=1		
		self.re_draw = False
		
	def show(self):		
		self.ui.show()
		if config.mmi_debug: 			
			print 'self.re_draw =', self.re_draw
			print 'self.ui.get_focus() =', self.ui.get_focus()
			#print 'self.ui.list.focus = ', self.ui.list.focus
		focus = self.ui.get_focus()
		if self.re_draw:
			self.ui.set_focus(focus, self.re_draw)  # UserInfomationWidget
		for ent in self.ui.list.entrys:
			ent.lostFocus()
		self.ui.list.entrys[focus].showFocus()	
		#self.ui.list.entrys[self.ui.list.focus].showFocus()	
		
	def activate(self, index):
		#print 'activate', index
		pass

	def get_automata_idx(self, name, casemode):
		#print 'UserInfo:get_automata_idx:name=',name,',casemode=',casemode
		for i, a in enumerate(config.automata_list_mult_num_symbol):
			n,c = a
			if n == name and (not c or c == casemode):
				#print 'UserInfo:get_automata_idx:name=',name,',casemode=',casemode,':i=',i
				return i
				
	# ka...2008.06.24: 
	def registering(self):		
		stage = phonesetting.AutoRegisteringStage()
		runtime.manager.change_stage(stage, True)			

	def checkSettings(self):
		self.EditedText = []
		for i in range(self.edit_entry_n):
			txtbuf = self.ui.list.entrys[i].get_text()
			self.EditedText.append(txtbuf)
			
		tel_num = self.EditedText[0]
		auth_name = self.EditedText[1]
		
		if status.voip_auth_pwd_type == 1:
			if self.original_hexa_type_auth_pwd_value == self.EditedText[2]:
				auth_pwd = 'HASH:'+self.EditedText[2]
			else:
				auth_pwd = self.EditedText[2]
		else:
			auth_pwd = self.EditedText[2]
		if config.mmi_debug: 
			print '## status.voip_auth_pwd_type =', status.voip_auth_pwd_type
			print '## 	new vdci_setting.auth_pwd = ', auth_pwd
		sip_uri = self.EditedText[3]
		domain = self.EditedText[4]
		proxy_addr = self.EditedText[5]
		proxy_port = self.EditedText[6]
		backup_proxy_addr = self.EditedText[7]
		backup_proxy_port = self.EditedText[8]
		primary_sbc_addr = self.EditedText[9]
		primary_sbc_port = self.EditedText[10]
		secondary_sbc_addr = self.EditedText[11]
		secondary_sbc_port = self.EditedText[12]
		import uiconfig
		# check tel num ------------
		msg = ''
		if not tel_num:
			roxia_trace('Check telnum fail')
			msg = _('Please input telephone number first.')
		elif not domain:
			roxia_trace('Check domain fail')
			msg = _('Please input domain name')
		# cscf/sbc address and port
		elif utils.check_private_range():
			# check sbc proxy
			print 'SBC1:', primary_sbc_addr, primary_sbc_port
			print 'SBC2:',secondary_sbc_addr, secondary_sbc_port
			
			#if (len(primary_sbc_addr) > 0) \
			#		and (len(primary_sbc_port) > 0) \
			#		and (len(secondary_sbc_addr) > 0 ) \
			#		and (len(secondary_sbc_port) > 0):
			if (len(primary_sbc_addr) > 0) \
					and (len(primary_sbc_port) > 0):
				pass
			else:
				roxia_trace('Check SBC fail')
				msg = _('Please input information relating to SBC.')
		elif not utils.check_private_range():
			# check public proxy
			print 'CSCF1:', proxy_addr, proxy_port
			print 'CSCF2:', backup_proxy_addr, backup_proxy_port			
			
			#if (len(proxy_addr) > 0) \
			#		and (len(proxy_port) > 0) \
			#		and (len(backup_proxy_addr) > 0) \
			#		and (len(backup_proxy_port) > 0):
			if (len(proxy_addr) > 0) \
					and (len(proxy_port) > 0):
				pass
			else:
				roxia_trace('Check CSCF fail')
				msg = _('Please input information relating to CSCF.')
		if msg:
			runtime.manager.stack_stage(NotifyStage(msg))
			self.re_draw = True
			return False
		else:
			vdci_setting.tel_num = tel_num
			vdci_setting.auth_name = auth_name
			vdci_setting.auth_pwd = auth_pwd
			vdci_setting.sip_uri = sip_uri
			vdci_setting.domain = domain
			vdci_setting.proxy_addr = proxy_addr
			vdci_setting.proxy_port = proxy_port
			vdci_setting.backup_proxy_addr = backup_proxy_addr
			vdci_setting.backup_proxy_port = backup_proxy_port
			vdci_setting.primary_sbc_addr = primary_sbc_addr
			vdci_setting.primary_sbc_port = primary_sbc_port
			vdci_setting.secondary_sbc_addr = secondary_sbc_addr
			vdci_setting.secondary_sbc_port = secondary_sbc_port
			vdci_setting.save()
			return True
	
		
	def handle_key(self,key):
		status.crnt_key = key
		if key == config.Menu1 or key =='OK':
			'''
			self.EditedText = []
			for i in range(self.edit_entry_n):
				txtbuf = self.ui.list.entrys[i].get_text()
				self.EditedText.append(txtbuf)
				
			vdci_setting.tel_num = self.EditedText[0]
			vdci_setting.auth_name = self.EditedText[1]
			
			if status.voip_auth_pwd_type == 1:
				if self.original_hexa_type_auth_pwd_value == self.EditedText[2]:
					vdci_setting.auth_pwd = 'HASH:'+self.EditedText[2]
				else:
					vdci_setting.auth_pwd = self.EditedText[2]
			else:
				vdci_setting.auth_pwd = self.EditedText[2]
			if config.mmi_debug: 
				print '## status.voip_auth_pwd_type =', status.voip_auth_pwd_type
				print '## 	new vdci_setting.auth_pwd = ', vdci_setting.auth_pwd
			vdci_setting.sip_uri = self.EditedText[3]
			vdci_setting.domain = self.EditedText[4]
			vdci_setting.proxy_addr = self.EditedText[5]
			vdci_setting.proxy_port = self.EditedText[6]
			vdci_setting.backup_proxy_addr = self.EditedText[7]
			vdci_setting.backup_proxy_port = self.EditedText[8]
			vdci_setting.primary_sbc_addr = self.EditedText[9]
			vdci_setting.primary_sbc_port = self.EditedText[10]
			vdci_setting.secondary_sbc_addr = self.EditedText[11]
			vdci_setting.secondary_sbc_port = self.EditedText[12]			
			'''
			if not self.checkSettings():
				return True
			
			#print '==>', self.ui.list.entrys[0].get_text(), setting.in_restrict			
			f = open('/usr/local/lgvp/cpeid.cfg','w')
			f.write("CPEID=%s\n" % vdci_setting.tel_num)
			f.close()

			#errorcode.set_idle_errmsg('')
			errorcode.set_idle_errmsg('', delay_msec=2000, refresh=False)
			
			os.system('sync')
			os.system('sync')
			utils.player.play_effect(config.SETTING_SUCCEEDED)
			#stage = NotifyStage(_('Set is saved'), uiconfig.baloon_setting_phone_icon)
			#runtime.manager.change_stage(stage)
			#runtime.manager.back_stage()
			#runtime.manager.stack_stage(stage)

			def reset_cb():
				pass
				'''
				import utils, time
				if runtime.vdciapp:
					runtime.vdciapp.req_deregister()
				time.sleep(1)
				utils.releaseDhcp()
#MMW	2008.07.07	when reboot send disassoc to AP and then unload the driver
				os.system('wlstop')
#end of MMW
#MMW 2008.06.25 when reboot is called, reset vega and DCP related GPIO pin				
				utils.vega_reset_together()
#end of MMW	
				time.sleep(1)
				os.system('reboot')
				'''
				
			#stage = NotifyStage(_('Setting saved.\nRebooting.\n'), uiconfig.baloon_setting_system_reset_icon, reset_cb)
			stage = NotifyStage(_('Set is saved'), uiconfig.baloon_setting_system_reset_icon, self.registering)
			runtime.manager.stack_stage(stage)

			
		elif key in ('Up', 'Down'):
			ret = self.ui.handle_key(key)			
			for ent in self.ui.list.entrys:
				ent.lostFocus()				
			status.RichTextFocus = 0
			if status.prev_tc != None:
				status.prev_tc.hide()
				status.prev_tc.free()
				status.prev_tc = None
			if status.prev_tc_box != None:
				status.prev_tc_box.hide()
				status.prev_tc_box.free()
				status.prev_tc_box = None

			if config.mmi_debug:
				print 'self.ui.list.focus=', self.ui.list.focus
			
			if self.ui.list.labels[self.ui.list.focus].RealText == _('Password.'):
				status.RichTextFocus = 1
			self.ui.list.entrys[self.ui.list.focus].showFocus()
			return ret
			
		elif key in ('Left', 'Right'):
			ret = self.ui.handle_key(key)	
			return ret
			
		elif key == config.CLEAR:
			#self.ui.list.entrys[self.ui.list.focus].handle_key(key)
			if len(self.ui.list.entrys[self.ui.list.focus].get_text()) > 0:
				self.ui.list.entrys[self.ui.list.focus].backspace(1)
			else:
				runtime.manager.back_stage()
			return True
			
		elif key == config.Menu4:
			if status.prev_tc != None:
				status.prev_tc.hide()
				status.prev_tc.free()
				status.prev_tc = None
			if status.prev_tc_box != None:
				status.prev_tc_box.hide()
				status.prev_tc_box.free()
				status.prev_tc_box = None
			runtime.manager.back_stage()
			return True

		#proxy address
		elif key == '*':
			#print 'change : * --> .'
			self.ui.insert_text(self.ui.list.entrys[self.ui.list.focus], '.')
		#elif key == '#' and self.flag == 0:
		#	return True

		elif key == config.Menu2:
			## KT_Req: Do not use Hexa mode 
			#if self.ui.list.focus == 2:
			#	if self.ui.right== 'Plain text':
			#		self.ui.set_right('Hexa')
			#		#print 'self.ui.list.entrys[self.ui.list.focus].get_text()=', self.ui.list.entrys[self.ui.list.focus].get_text()
			#		#self.EditedText[2] = self.ui.list.entrys[self.ui.list.focus].get_text()
			#		#self.EditedText[2] = utils.change_ascii_to_hexa(self.EditedText[2])					
			#		#self.ui.list.entrys[self.ui.list.focus].set_text(self.EditedText[2])
			#		self.ui.list.entrys[self.ui.list.focus].set_text('')
			#		status.voip_auth_pwd_type = 1
			#	else: # HEXA -->Plain text
			#		self.ui.set_right('Plain text')
			#		#print 'self.ui.list.entrys[self.ui.list.focus].get_text()=', self.ui.list.entrys[self.ui.list.focus].get_text()
			#		#self.EditedText[2] = self.ui.list.entrys[self.ui.list.focus].get_text()
			#		#self.EditedText[2]= utils.change_hexa_to_plain(vdci_setting.auth_pwd[5:])
			#		#self.ui.list.entrys[self.ui.list.focus].set_text(self.EditedText[2])
			#		self.ui.list.entrys[self.ui.list.focus].set_text('')
			#		status.voip_auth_pwd_type = 0
			#if config.mmi_debug: 
			#	print 'self.ui.right = ', self.ui.right
			#	print 'status.voip_auth_pwd_type =', status.voip_auth_pwd_type
			return True
		
		elif key == config.Menu3:
			if config.mmi_debug: 
				print 'self.flag =', self.flag
				print 'self.ui.list.focus=',self.ui.list.focus
				#print 'self.ui.list.entrys[self.ui.list.focus] = ', self.ui.list.entrys[self.ui.list.focus]
			if self.flag == 0:
				self.ui.set_automata(self.ui.list.entrys[self.ui.list.focus], 'multitap', 'lower')
				self.ui.update_automata_icon(self.ui.list.entrys[self.list.focus])
				self.flag = 1
			elif self.flag == 1:
				self.ui.set_automata(self.ui.list.entrys[self.ui.list.focus], '123', False)
				self.ui.update_automata_icon(self.ui.list.entrys[self.list.focus])
				self.flag = 0
			else:
				# KA: [20070831] hangul lvp-2000
				# vpark 2006.08.28 automata	
				'''
				self.ui.automata_idx = utils.get_automata_idx(*self.ui.automata)
				if setting.lang == 'Korean':			
					self.ui.automata_idx = (self.ui.automata_idx + 1) % len(config.automata_list_hangul)	
					self.ui.automata = config.automata_list_hangul[self.ui.automata_idx]			
				else:			
					self.ui.automata_idx = (self.ui.automata_idx + 1) % len(config.automata_list)	
					self.ui.automata = config.automata_list[self.ui.automata_idx]					
				'''

				self.ui.automata_idx = self.get_automata_idx(*self.ui.automata)
				self.ui.automata_idx = (self.ui.automata_idx + 1) % len(config.automata_list_mult_num_symbol)	
				self.ui.automata = config.automata_list_mult_num_symbol[self.ui.automata_idx]					

				if config.mmi_debug: 
					print '## self.ui.automata=', self.ui.automata
					print '## self.ui.automata[0]=', self.ui.automata[0]					
				
				if self.ui.automata[0] == 'symbol':
					self.ui.update_automata_icon_symbol()					
					self.re_draw = True
				else:
					self.ui.set_automata(self.ui.list.entrys[self.ui.list.focus], *self.ui.automata)		
					self.ui.update_automata_icon(self.ui.list.entrys[self.ui.list.focus])
				
				return True	
				# KA: [20070831] hangul lvp-2000 ==
			
		else:
			if key == config.Red:
				if status.prev_tc != None:
					status.prev_tc.hide()
					status.prev_tc.free()
					status.prev_tc = None
				if status.prev_tc_box != None:
					status.prev_tc_box.hide()
					status.prev_tc_box.free()
					status.prev_tc_box = None
				runtime.manager.back_stage()
			if config.mmi_debug: print 'HK: self.ui.list.focus=', self.ui.list.focus
			ret = self.ui.list.entrys[self.ui.list.focus].handle_key(key)
			return ret

	def destroy(self):
		self.ui.destroy()		
		if status.prev_tc != None:
			status.prev_tc.free()
			status.prev_tc = None
		if status.prev_tc_box != None:
			status.prev_tc_box.free()
			status.prev_tc_box = None


class Proxy(ListStage):
	icon = uiconfig.setting_voip_icon
	def __init__(self):
		self.title = _('PROXY')
		self.choice = (_('Proxy address')+'1', _('Proxy port')+'1', _('Proxy address')+'2', _('Proxy port')+'2', _('SBC address')+'1', _('SBC port')+'1', _('SBC address')+'2',  _('SBC port')+'2')
	
		ListStage.__init__(self)
	def set_cb(self, ui):
		text = ui.get_text()
		if len(text) == 0:
			runtime.manager.stack_stage(VoIPSettingNotifyStage(_('No text inserted.')))
		else:
			check_voip_change(self.value, text)
			if self.index == 0:		vdci_setting.set_proxy_addr(text)
			elif self.index == 1:	vdci_setting.set_proxy_port(text)
			elif self.index == 2:	vdci_setting.set_backup_proxy_addr(text)
			elif self.index == 3:	vdci_setting.set_backup_proxy_port(text)
			elif self.index == 4:	vdci_setting.set_primary_sbc_addr(text)
			elif self.index == 5:	vdci_setting.set_primary_sbc_port(text)
			elif self.index == 6:	vdci_setting.set_secondary_sbc_addr(text)
			elif self.index == 7:	vdci_setting.set_secondary_sbc_port(text)

			runtime.manager.change_stage(VoIPSettingNotifyStage(self.subtitle+' ' +_('set')))

	def activate(self, index):
		if index == 0:
			value = vdci_setting.proxy_addr
			title = _('PROXY ADDRESS')
			subtitle = _('Proxy address')
			max = 50
		elif index == 1:
			value = vdci_setting.proxy_port
			title = _('PROXY PORT')
			subtitle = _('Proxy port')
			max = 5
		elif index == 2:
			value = vdci_setting.backup_proxy_addr
			title = _('BACKUP ROXY ADDRESS')
			subtitle = _('Backup proxy address')
			max = 50
		elif index == 3:
			value = vdci_setting.backup_proxy_port
			title = _('BACKUP PROXY PORT')
			subtitle = _('Backup proxy port')
			max = 5
		elif index ==4:
			value = vdci_setting.primary_sbc_addr
			title = _('PRIMARY PROXY ADDRESS')
			subtitle = _('Primary proxy address')
			max = 50
		elif index ==5:
			value = vdci_setting.primary_sbc_port
			title = _('PRIMARY PROXY PORT')
			subtitle = _('Primary proxy port')
			max = 5
		elif index ==6:
			value = vdci_setting.secondary_sbc_addr
			title = _('SECONDARY PROXY ADDRESS')
			subtitle = _('Secondary proxy address')
			max = 50
		elif index ==7:
			value = vdci_setting.secondary_sbc_port
			title = _('SECONDARY PROXY PORT')
			subtitle = _('Secondary proxy port')
			max = 5
			
		self.value = value
		self.index = index
		self.subtitle = subtitle
		stage = VoIPEditor(title, subtitle, self.set_cb, text=value, textmax = max, ischr=True, only_num = 0)
		runtime.manager.stack_stage(stage)


class TestMenuRegistrationStage(ListStage):
	name = 'testmenu registration'
	def __init__(self):
		self.title = _('REGISTRATION')
		self.choice = []
		
		if status.get_regstatus() == 1:
			self.choice = _('De-register'),
		else:
			self.choice = _('Register'),
		ListStage.__init__(self, self.choice)

	def activate(self, index):
		import profile
		if profile.ip_mode == 0 and index == 0: # pstn, register
			message = _('Cannot setup in PSTN mode.')
			stage = VoIPSettingNotifyStage(message)
			runtime.manager.change_stage(stage)
			return True
		if self.choice[index] == _('Register'):
			runtime.SP_context.goIdleState()
			
			status.voip_setting_changed = False
			runtime.manager.stack_stage(phonesetting.AutoRegisteringStage)
		elif self.choice[index] == _('De-register'):
			status.voip_setting_changed = False
			# KA: [20071119] TI IMS subscriber
			#if setting.subscriber:
			#runtime.manager.stack_stage(ReleaseSubscriptionStage)
			#else:
			runtime.manager.stack_stage(phonesetting.DeRegisteringStage)
			# KA: [20071119] TI IMS subscriber
		elif self.choice[index] ==  _('Expires'):
			expires = vdci_setting.expires
			stage = VoIPEditor(_('EXPIRES'), _('Sec (60~7200)'), self.expires_cb, text=expires, textmax = 4, only_num = 2)
			runtime.manager.stack_stage(stage)
		elif self.choice[index] ==  _('Register port'):
			reg_port = vdci_setting.register_port
			stage = VoIPEditor(_('REGISTER PORT'), _('Register port'), self.registerport_cb, text=reg_port, textmax = 5, only_num = 2)
			runtime.manager.stack_stage(stage)
		# KA: [20071105] TI IMS subscriber
		elif self.choice[index] == _('Subscriber'):
			runtime.manager.stack_stage(SubscriptionStage)
		# KA: [20071105] TI IMS subscriber ==

	def show(self):
		if status.get_regstatus() == 1:
			self.choice = _('De-register'),
		else:
			self.choice = _('Register'),
			
		ListStage.change_choice(self, self.choice)
		ListStage.show(self)

	def expires_cb(self, ui):
		text = ui.get_text()
		if len(text) == 0:
			runtime.manager.stack_stage(VoIPSettingNotifyStage(_('No text inserted.')))
		elif int(text) < 60 or int(text) > 7200:
			runtime.manager.stack_stage(VoIPSettingNotifyStage(_('Out of range')))
		else:
			check_voip_change(vdci_setting.expires, text)
			vdci_setting.set_expires(text)
			runtime.manager.change_stage(VoIPSettingNotifyStage(_('Expires set')))

	def registerport_cb(self, ui):
		text = ui.get_text()
		if len(text) == 0:
			runtime.manager.stack_stage(VoIPSettingNotifyStage(_('No text inserted.')))
		elif int(text) < 1024 or int(text) > 65535:
			runtime.manager.stack_stage(VoIPSettingNotifyStage(_('Out of range')))
		else:
			check_voip_change(vdci_setting.register_port, text)
			vdci_setting.set_register_port(text)
			runtime.manager.change_stage(VoIPSettingNotifyStage(_('Register port set')))

	def register(self):
		stage = RegisteringStage
		runtime.manager.stack_stage(stage)
		#runtime.manager.change_stage(stage)
		return False

	def deregister(self):
		stage = DeRegisteringStage
		runtime.manager.stack_stage(stage)
		return False

        def destroy(self):
		ListStage.destroy(self)


class RegistrationStage(ListStage):
	name = 'registration'
	icon = uiconfig.setting_voip_icon
	def __init__(self):
		self.title = _('REGISTRATION')
		self.choice = []
		
		if status.debug_mode:
			self.choice = [_('Register'), _('Expires')]
		else:
			self.choice = [_('Register'), ] # debug disable시 register메뉴만 있음
		# KA: [20071013] TI IMS setting
		#if status.registered_status == 1 and status.subscriber == False and setting.subscriber == 1:
		#	self.choice.insert(1,_('Subscriber'))
		#	self.choice.insert(2,_('De-register'))
		if status.get_regstatus() == 1:
			self.choice.insert(1,_('De-register'))
		self.choice = tuple(self.choice)
		# KA: [20071013] TI IMS setting ==
		ListStage.__init__(self, self.choice)

	def activate(self, index):
		import profile
		if profile.ip_mode == 0 and index == 0: # pstn, register
			message = _('Cannot setup in PSTN mode.')
			stage = VoIPSettingNotifyStage(message)
			runtime.manager.change_stage(stage)
			return True
		if self.choice[index] == _('Register'):
			status.voip_setting_changed = False
			runtime.manager.stack_stage(phonesetting.AutoRegisteringStage)
		elif self.choice[index] == _('De-register'):
			status.voip_setting_changed = False
			# KA: [20071119] TI IMS subscriber
			if setting.subscriber:
				runtime.manager.stack_stage(ReleaseSubscriptionStage)
			else:
				runtime.manager.stack_stage(phonesetting.DeRegisteringStage)
			# KA: [20071119] TI IMS subscriber
		elif self.choice[index] ==  _('Expires'):
			expires = vdci_setting.expires
			stage = VoIPEditor(_('EXPIRES'), _('Sec (60~7200)'), self.expires_cb, text=expires, textmax = 4, only_num = 2)
			runtime.manager.stack_stage(stage)
		elif self.choice[index] ==  _('Register port'):
			reg_port = vdci_setting.register_port
			stage = VoIPEditor(_('REGISTER PORT'), _('Register port'), self.registerport_cb, text=reg_port, textmax = 5, only_num = 2)
			runtime.manager.stack_stage(stage)
		# KA: [20071105] TI IMS subscriber
		elif self.choice[index] == _('Subscriber'):
			runtime.manager.stack_stage(SubscriptionStage)
		# KA: [20071105] TI IMS subscriber ==

	def show(self):
		self.choice = []
		if status.debug_mode:
			self.choice = [_('Register'), _('Expires')]
		else:
			self.choice = [_('Register'), ] # debug disable시 register메뉴만 있음
		# KA: [20071013] TI IMS setting
		#if status.registered_status == 1 and status.subscriber == False and setting.subscriber == 1:
		#	self.choice.insert(1,_('Subscriber'))
		#	self.choice.insert(2,_('De-register'))
		if status.get_regstatus() == 1:
			self.choice.insert(1,_('De-register'))
		self.choice = tuple(self.choice)
		# KA: [20071013] TI IMS setting ==
		ListStage.change_choice(self, self.choice)
		ListStage.show(self)

	def expires_cb(self, ui):
		text = ui.get_text()
		if len(text) == 0:
			runtime.manager.stack_stage(VoIPSettingNotifyStage(_('No text inserted.')))
		elif int(text) < 60 or int(text) > 7200:
			runtime.manager.stack_stage(VoIPSettingNotifyStage(_('Out of range')))
		else:
			check_voip_change(vdci_setting.expires, text)
			vdci_setting.set_expires(text)
			runtime.manager.change_stage(VoIPSettingNotifyStage(_('Expires set')))

	def registerport_cb(self, ui):
		text = ui.get_text()
		if len(text) == 0:
			runtime.manager.stack_stage(VoIPSettingNotifyStage(_('No text inserted.')))
		elif int(text) < 1024 or int(text) > 65535:
			runtime.manager.stack_stage(VoIPSettingNotifyStage(_('Out of range')))
		else:
			check_voip_change(vdci_setting.register_port, text)
			vdci_setting.set_register_port(text)
			runtime.manager.change_stage(VoIPSettingNotifyStage(_('Register port set')))

	def register(self):
		stage = RegisteringStage
		runtime.manager.stack_stage(stage)
		#runtime.manager.change_stage(stage)
		return False

	def deregister(self):
		stage = DeRegisteringStage
		runtime.manager.stack_stage(stage)
		return False

        def destroy(self):
		ListStage.destroy(self)

# KA: [20071105] TI IMS subscriber
class SubscriptionStage(Stage):
	name = "Subscription"
	def __init__(self, dereg_first=True):
		status.supervision_not_allowed = 1
		import ui
		self.reg_message = _('Send a subscription.')+'\n'+_('Please wait for a moment.')
		self.ui = ui.VideoCallRegisteringUI(show_bg=False, msg=self.reg_message)
# for TEST
#		runtime.vdciapp.req_desubscriber()
#		import time
#		time.sleep(1)
# for TEST ==
		status.subscriber =  False
		runtime.vdciapp.req_subscriber()
		self.tag_subscriber = utils.Timer(config.timeoutSubscriber, self.subscriber_failed)

	def subscriber_failed(self):
		self.tag_subscriber = None
		message = _('Subscription failed')
		utils.player.play_effect(config.SETTING_FAILED)
		stage = VoIPSettingNotifyStage(message)
		runtime.manager.change_stage(stage)

	def subscriber_sucessed(self):
		self.tag_subscriber = None
		status.subscriber = True
		message = _('Subscription success')
		utils.player.play_effect(config.SETTING_SUCCEEDED)
		stage = VoIPSettingNotifyStage(message)
		runtime.manager.change_stage(stage)


class ReleaseSubscriptionStage(Stage):
	name = "ReleaseSubscription"
	def __init__(self, dereg_first=True):
		status.supervision_not_allowed = 1
		import ui
		self.reg_message = _('Release subscription.')+'\n'+_('Please wait for a moment.')
		self.ui = ui.VideoCallRegisteringUI(show_bg=False, msg=self.reg_message)
		self.req_desubscriber()	
		self.tag_subscriber = None

	def req_desubscriber(self):
		if runtime.vdciapp.subscriber_success:	
			runtime.vdciapp.req_desubscriber()
			self.tag_subscriber = utils.Timer(config.timeoutSubscriber, self.desubscriber_failed)
		else:
			self.go_deregistering()
			
	def desubscriber_failed(self):
		self.tag_subscriber = None
		message = _('Release subscription failed')
		stage = VoIPSettingNotifyStage(message, self.go_deregistering)
		runtime.manager.change_stage(stage)

	def desubscriber_sucessed(self):
		self.tag_subscriber = None
		status.subscriber = False
		message = _('Release subscription success')
		stage = VoIPSettingNotifyStage(message, self.go_deregistering)
		runtime.manager.change_stage(stage)

	def go_deregistering(self):
		runtime.manager.change_stage(phonesetting.DeRegisteringStage)


class PrecondtionSetStage(ListStage):
	name = 'PrecondtionSet'
	icon = uiconfig.setting_voip_icon
	def __init__(self):
		self.title = _('PRECONDITION SET')
		ListStage.__init__(self)

	def show(self):
		self.update_addlist()
		ListStage.show(self)

	def update_addlist(self):
		self.choice = []
		if vdci_setting.rsvp_mode =='1':
			self.choice = [_('Disable')]
		else:
			self.choice = [_('Enable')]
		self.change_choice(self.choice)

	def activate(self, index):
		current_value = vdci_setting.rsvp_mode
		if self.choice[index] == _('Enable'):
			vdci_setting.set_precondition('1')
			message = _('Precondition enable')
		elif self.choice[index] == _('Disable'):
			vdci_setting.set_precondition('0')
			message = _('Precondition disable')
		new_value = vdci_setting.rsvp_mode
		check_voip_change(current_value, new_value)
		stage = VoIPSettingNotifyStage(message)
		runtime.manager.change_stage(stage)
# KA: [20071105] TI IMS subscriber ==

# KA: [20071214] TI IMS subscriber set
class SubscriberSetStage(ListStage):
	name = 'SubscriberSet'
	icon = uiconfig.setting_voip_icon
	def __init__(self):
		self.title = _('SUBSCRIBER SET')
		ListStage.__init__(self)

	def show(self):
		self.update_addlist()
		ListStage.show(self)

	def update_addlist(self):
		self.choice = []
		if setting.subscriber == 1:
			self.choice = [_('Disable'), _('Expires')]
		else:
			self.choice = [_('Enable'), _('Expires')]
		self.change_choice(self.choice)

	def activate(self, index):
		if self.choice[index] ==  _('Expires'):
			expires = vdci_setting.subscriber_expires
			stage = VoIPEditor(_('EXPIRES'), _('Sec (60~600000)'), self.expires_cb, text=expires, textmax = 6, only_num = 2)
			runtime.manager.stack_stage(stage)
			return
		if self.choice[index] == _('Enable'):
			setting.set_subscriber(1)
			message = _('Subscriber enable')
		elif self.choice[index] == _('Disable'):
			setting.set_subscriber(0)
			message = _('Subscriber disable')
		stage = VoIPSettingNotifyStage(message)
		runtime.manager.change_stage(stage)

	def expires_cb(self, ui):
		text = ui.get_text()
		if len(text) == 0:
			runtime.manager.stack_stage(VoIPSettingNotifyStage(_('No text inserted.')))
		elif int(text) < 60 or int(text) > 600000:
			runtime.manager.stack_stage(VoIPSettingNotifyStage(_('Out of range')))
		else:
			check_voip_change(vdci_setting.subscriber_expires, text)
			vdci_setting.set_subscriber_expires(text)
			runtime.manager.change_stage(VoIPSettingNotifyStage(_('Expires set')))
		
# KA: [20071214] TI IMS subscriber set ==


class RegisteringStage(Stage):
	name = "registering"
	def __init__(self):
		status.supervision_not_allowed = 1
		status.set_register_mode(status.Registering)
		
		import ui
		self.ui = ui.VideoCallRegisteringUI(False)
		self.tag_register = None
		status.videocall_dimension = setting.video_dimension

		def do_reload():
			phonesetting.vdci_reload()
			return False

		self.reload_tag = utils.Timer(100, do_reload)

		self.tag_register = utils.Timer(config.timeoutRegister, self.register_failed)

	def handle_key(self, key):
		if key == config.Menu2:
			if status.get_register_mode() != status.Registering:
				roxia_trace('** ignore END key while registering.. **')
				return False
			self.register_cancel()
			return True
		elif key == config.OnHook:
			if status.get_register_mode() != status.Registering:
				return False
			if status.modem_audio_state == status.HS:
				self.register_cancel()
			else:
				pass
		elif key == config.Red:
			#if status.registered_status != status.Registering:
			if status.get_register_mode() != status.Registering:
				return False
			if status.modem_audio_state == status.SPK:
				self.register_cancel()
			else:
				pass
		return False

	def register_sucessed(self):
		roxia_trace('RegisteringStage.register_sucessed()')
		self.tag_register = None
		status.set_register_mode(status.Registered)

		import profile
		if profile.profile.get_profile() == 1: # lan
			status.LanConnected = True
		message = _('Registration succeeded')
		
		status.set_regstatus(1)

		def go_idle():
			runtime.manager.back_stage('idle')
#Roxia Begin smyook 06.03.03 auto configuration
			status.critical_entered = True
#Roxia End smyook
			# KA: [20071105] TI IMS subscriber
			# KA: [20080510] new subscriber
			#if setting.subscriber:
			#	runtime.manager.stack_stage(SubscriptionStage)
			#else:
			#	runtime.vdciapp.req_subscriber()
			# KA: [20071105] TI IMS subscriber ==
			return
		
		test_stage = runtime.manager.find_stage('testmenu registration', True)

		if test_stage:
			stage = VoIPSettingNotifyStage(message)
		else:
			stage = VoIPSettingNotifyStage(message, go_idle)

		runtime.manager.change_stage(stage)

	def register_failed(self, msg=None):
		roxia_trace('***************** register_failed() *1************')
		self.tag_register = None

		status.set_register_mode(status.NotRegistered)

		status.set_regstatus(0)
		#RegistrationStage.ch_choice
		if not msg:
			msg = _('Registration failed')
#Roxia Begin smyook 06.03.16
		status.critical_entered = True
		stage = VoIPSettingNotifyStage(msg)
#Roixa End smyook
		runtime.manager.change_stage(stage)

	def register_cancel(self):
		roxia_trace('***************** register_calcel() *************')
		self.tag_register = None
		status.set_register_mode(status.NotRegistered)

		message = _('Registration cancelled')
		stage = VoIPSettingNotifyStage(message)
		runtime.manager.change_stage(stage)

	def register_error(self):
		roxia_trace('***************** register_error() *************')
		temp_mode = status.get_register_mode()
		status.set_register_mode(status.NotRegistered)
		self.tag_register = None

		if temp_mode != status.Registering:
			return

		message = _('register failed')
		stage = VoIPSettingNotifyStage(message)
		runtime.manager.change_stage(stage)

	def destroy(self):
		self.tag_register = None
		Stage.destroy(self)
		status.supervision_not_allowed = 0

class DeRegisteringStage(Stage):
	name = "deregistering"
	def __init__(self):

		status.set_register_mode(status.Registering)
		import ui
		self.ui = ui.VideoCallDeRegisteringUI(False)
		self.tag_register = None
		status.videocall_dimension = setting.video_dimension
		self.request_deregister()

	def handle_key(self, key):
		if key == config.Menu2:
			if status.get_register_mode() != status.Registering:
				return False
			self.deregister_cancel()
			return True
		elif key == config.OnHook:
			if status.get_register_mode() != status.Registering:
				return False
			if status.modem_audio_state == status.HS:
				self.deregister_cancel()
			else:
				pass
		elif key == config.Red:
			if status.registere_mode != status.Registering:
				return False
			if status.modem_audio_state == status.SPK:
				self.deregister_cancel()
			else:
				pass
		return False

	def request_deregister(self):
		if runtime.vdciapp:
			runtime.vdciapp.req_deregister()
		self.tag_register = utils.Timer(config.timeoutDeregister, self.deregister_failed)
		return False

	def deregister_sucessed(self):
		roxia_trace('DeRegisteringStage.deregister_sucessed()')
		self.tag_register = None

		status.set_register_mode(status.NotRegistered)
		message = _('De-registration succeeded')
		status.set_regstatus(0)

		stage = VoIPSettingNotifyStage(message)
		runtime.manager.change_stage(stage)

	def deregister_failed(self):
		roxia_trace('***************** deregister_failed() *************')
		self.tag_register = None
		if status.get_register_mode()!= status.Registering:
			return

		status.set_register_mode(status.NotRegistered)
		status.set_regstatus(0)
		#RegistrationStage.ch_choice
		message = _('De-registration failed')
		stage = VoIPSettingNotifyStage(message)
		runtime.manager.change_stage(stage)

	def deregister_cancel(self):
		roxia_trace('***************** deregister_calcel() *************')
		self.tag_register = None
		if status.get_register_mode() != status.Registering:
			return

		message = _('De-registration cancelled')
		stage = VoIPSettingNotifyStage(message)
		runtime.manager.change_stage(stage)

	def deregister_error(self):
		roxia_trace('***************** deregister_error() *************')
		temp_mode = status.get_register_mode()
		self.tag_register = None

		status.set_register_mode(status.NotRegistered)
		status.set_regstatus(0)

		if temp_mode != status.Registering:
			return

		message = _('de-register failed')
		stage = VoIPSettingNotifyStage(message)
		runtime.manager.change_stage(stage)

		def destroy(self):
			self.tag_register = None
			Stage.destroy(self)


class Ports(ListStage):

	icon = uiconfig.setting_voip_icon

	def __init__(self):
		self.title = _('PORTS')
		self.choice = (_('Audio'), _('Video'), _('Local'))
		ListStage.__init__(self)

	def activate(self, index):
		if index == 0:
			audio_port = vdci_setting.audio_port
			stage = VoIPEditor(_('AUDIO'), _('Audio'), self.audio_cb, text=str(audio_port), textmax = 5, only_num = 2)
		elif index == 1:
			video_port = vdci_setting.video_port
			stage = VoIPEditor(_('VIDEO'), _('Video'), self.video_cb, text=str(video_port), textmax = 5, only_num = 2)
		elif index == 2:
			local_port = vdci_setting.local_port
			stage = VoIPEditor(_('LOCAL'), _('Local'), self.local_cb, text=str(local_port), textmax = 5, only_num = 2)

		runtime.manager.stack_stage(stage)

	def audio_cb(self, ui):
		text = ui.get_text()
		if len(text) == 0:
			runtime.manager.stack_stage(VoIPSettingNotifyStage(_('No text inserted.')))
		elif int(text) < 1024 or int(text) > 65535:
			runtime.manager.stack_stage(VoIPSettingNotifyStage(_('Out of range')))
		else:
			check_voip_change(vdci_setting.audio_port, text)
			vdci_setting.set_audio_port(text)
			runtime.manager.change_stage(VoIPSettingNotifyStage(_('Audio port set')))

	def video_cb(self, ui):
		text = ui.get_text()
		if len(text) == 0:
			runtime.manager.stack_stage(VoIPSettingNotifyStage(_('No text inserted.')))
		elif int(text) < 1024 or int(text) > 65535:
			runtime.manager.stack_stage(VoIPSettingNotifyStage(_('Out of range')))
		else:
			check_voip_change(vdci_setting.video_port, text)
			vdci_setting.set_video_port(text)
			runtime.manager.change_stage(VoIPSettingNotifyStage(_('Video port set')))

	def local_cb(self, ui):
		text = ui.get_text()
		if len(text) == 0:
			runtime.manager.stack_stage(VoIPSettingNotifyStage(_('No text inserted.')))
		elif int(text) < 1024 or int(text) > 65535:
			runtime.manager.stack_stage(VoIPSettingNotifyStage(_('Out of range')))
		else:
			check_voip_change(vdci_setting.local_port, text)
			vdci_setting.set_local_port(text)
			runtime.manager.change_stage(VoIPSettingNotifyStage(_('Local port set')))

class PacketPstnG723Stage(ListStage):
	def __init__(self):
		self.title = 'pstn_g723_pkt_dur'
		self.choice = ('30', '60', '90', '120')

		self.cur_index = 0
		value = tup_setting.pstn_g723_pkt_dur
		value = str(value)
		if  value in self.choice:
			tlist = list(self.choice)
			self.cur_index = tlist.index(value)

		ListStage.__init__(self, self.choice, self.title, None)
		self.ui.set_focus(self.cur_index)

	def activate(self, index):
		new_value = int(self.choice[index])
		tup_setting.set_pstn_g723(new_value)
		runtime.manager.change_stage(VoIPSettingNotifyStage(_('Packets set')))


class PacketPstnG729Stage(ListStage):
	def __init__(self):
		self.title = 'pstn_g729_pkt_dur'
		self.cur_index = 0
		self.choice = ('10', '20', '30', '40', '50', '60', '70', '80', '90', '100', '110', '120')
	
		value = tup_setting.pstn_g729_pkt_dur
		value = str(value)
		if  value in self.choice:
			tlist = list(self.choice)
			self.cur_index = tlist.index(value)

		ListStage.__init__(self, self.choice, self.title, None)
		self.ui.set_focus(self.cur_index)

	def activate(self, index):
		new_value = int(self.choice[index])
		tup_setting.set_pstn_g729(new_value)
		runtime.manager.change_stage(VoIPSettingNotifyStage(_('Packets set')))

class PacketPstnG711Stage(ListStage):
	def __init__(self):
		self.title = 'pstn_g711_pkt_dur'
		self.choice = ('10', '20', '30', '40')

		self.cur_index = 0
		value = tup_setting.pstn_g711_pkt_dur
		value = str(value)
		if  value in self.choice:
			tlist = list(self.choice)
			self.cur_index = tlist.index(value)

		ListStage.__init__(self, self.choice, self.title, None)
		self.ui.set_focus(self.cur_index)

	def activate(self, index):
		new_value = int(self.choice[index])
		tup_setting.set_pstn_g711(new_value)
		runtime.manager.change_stage(VoIPSettingNotifyStage(_('Packets set')))

class PacketPstnAmrStage(ListStage):
	def __init__(self):
		self.title = 'pstn_amr_pkt_dur'
		self.choice = ('20', '40', '60', '80', '100', '120')

		self.cur_index = 0
		value = tup_setting.pstn_amr_pkt_dur
		value = str(value)
		if  value in self.choice:
			tlist = list(self.choice)
			self.cur_index = tlist.index(value)

		ListStage.__init__(self, self.choice, self.title, None)
		self.ui.set_focus(self.cur_index)

	def activate(self, index):
		new_value = int(self.choice[index])
		tup_setting.set_pstn_amr(new_value)
		runtime.manager.change_stage(VoIPSettingNotifyStage(_('Packets set')))

class PacketIPG723Stage(ListStage):
	def __init__(self):
		self.title = 'ip_g723_pkt_dur'
		self.choice = ('30', '60', '90', '120')

		self.cur_index = 0
		value = tup_setting.ip_g723_pkt_dur
		value = str(value)
		if value in self.choice:
			tlist = list(self.choice)
			self.cur_index = tlist.index(value)

		ListStage.__init__(self, self.choice, self.title, None)
		self.ui.set_focus(self.cur_index)

	def activate(self, index):
		new_value = int(self.choice[index])
		tup_setting.set_ip_g723(new_value)
		runtime.manager.change_stage(VoIPSettingNotifyStage(_('Packets set')))

class PacketIPG729Stage(ListStage):
	def __init__(self):
		self.title = 'ip_g729_pkt_dur'
		self.choice = ('10', '20', '30', '40', '50', '60', '70', '80', '90', '100', '110', '120')

		self.cur_index = 0
		value = tup_setting.ip_g729_pkt_dur
		value = str(value)
		if  value in self.choice:
			tlist = list(self.choice)
			self.cur_index = tlist.index(value)

		ListStage.__init__(self, self.choice, self.title, None)
		self.ui.set_focus(self.cur_index)

	def activate(self, index):
		new_value = int(self.choice[index])
		tup_setting.set_ip_g729(new_value)
		runtime.manager.change_stage(VoIPSettingNotifyStage(_('Packets set')))


class PacketIPG711Stage(ListStage):
	def __init__(self):
		self.title = 'ip_g711_pkt_dur'
		self.choice = ('10', '20', '30', '40')

		self.cur_index = 0
		value = tup_setting.ip_g711_pkt_dur
		value = str(value)
		if  value in self.choice:
			tlist = list(self.choice)
			self.cur_index = tlist.index(value)

		ListStage.__init__(self, self.choice, self.title, None)
		self.ui.set_focus(self.cur_index)

	def activate(self, index):
		new_value = int(self.choice[index])
		tup_setting.set_ip_g711(new_value)
		runtime.manager.change_stage(VoIPSettingNotifyStage(_('Packets set')))

class PacketIPAmrStage(ListStage):
	def __init__(self):
		self.title = 'ip_amr_pkt_dur'
		self.choice = ('20', '40', '60', '80', '100', '120')

		self.cur_index = 0
		value = tup_setting.ip_amr_pkt_dur
		value = str(value)
		if  value in self.choice:
			tlist = list(self.choice)
			self.cur_index = tlist.index(value)

		ListStage.__init__(self, self.choice, self.title, None)
		self.ui.set_focus(self.cur_index)

	def activate(self, index):
		new_value = int(self.choice[index])
		tup_setting.set_ip_amr(new_value)
		runtime.manager.change_stage(VoIPSettingNotifyStage(_('Packets set')))

class PacketHighAmrStage(ListStage):
	def __init__(self):
		self.title = 'high_amr_codec'
		self.choice = ('0', '1')

		self.cur_index = 0
		value = tup_setting.high_amr_codec
		value = str(value)
		if  value in self.choice:
			tlist = list(self.choice)
			self.cur_index = tlist.index(value)

		ListStage.__init__(self, self.choice, self.title, None)
		self.ui.set_focus(self.cur_index)

	def activate(self, index):
		new_value = int(self.choice[index])
		tup_setting.set_high_amr(new_value)
		runtime.manager.change_stage(VoIPSettingNotifyStage(_('Packets set')))

class Packets(ListStage):
	icon = uiconfig.setting_voip_icon

	def __init__(self):
		self.title = _('PACKETS')
		self.choice = (_('pstn_g723_pkt_dur'), _('pstn_g729_pkt_dur'), _('pstn_g711_pkt_dur'), _('pstn_amr_pkt_dur'), \
				_('ip_g723_pkt_dur'), _('ip_g729_pkt_dur'), _('ip_g711_pkt_dur'), _('ip_amr_pkt_dur'), _('high_amr_codec'))

		ListStage.__init__(self)
	def activate(self, index):
		stage = (PacketPstnG723Stage, PacketPstnG729Stage, PacketPstnG711Stage, PacketPstnAmrStage, \
				PacketIPG723Stage, PacketIPG729Stage, PacketIPG711Stage, PacketIPAmrStage, PacketHighAmrStage)[index]
		runtime.manager.stack_stage(stage)

# KA: [20071006] TI IMS Codec Priority
class CodecPriority(ListStage):
	icon = uiconfig.setting_voip_icon
	domonitor_forbidden = True
	

	def __init__(self):
		self.title = _('VIDEO/AUDIO SETTING')
		self.choice = (_('Voice codec settings'), _('Video codec settings'), _('Video quality'), 'CTBW', _('Set Bandwidth'))
		
		ListStage.__init__(self)
	
	def activate(self, index):
		if index == 0:
			runtime.manager.stack_stage(AudioCodecPriority)
		elif index == 1:
			runtime.manager.stack_stage(VideoCodecPriority)
		elif index == 2:
			import videosetting
			runtime.manager.stack_stage(videosetting.VideoFluencyForAdminStage)
		#elif index == 3:
		#	import videosetting
		#	runtime.manager.stack_stage(videosetting.VideoDimensionStage)
		elif index == 3:
			ctbw = vdci_setting.ctbw
			stage = VoIPEditor(_('CTBW'), _('CTBW (80~800)'), self.ctbw_cb, text=str(ctbw), textmax = 3, only_num = 2)
			runtime.manager.stack_stage(stage)
		elif index == 4:
			value = setting.video_bitrate
			stage = VoIPEditor(_('Bitrate'), _('Bitrate (0~1000000)'), self.bitrate_cb, text=str(value), textmax = 7, only_num = 2)
			runtime.manager.stack_stage(stage)			
			
	def bitrate_cb(self, ui):
		text = ui.get_text()
		if len(text) == 0:
			runtime.manager.stack_stage(VoIPSettingNotifyStage(_('No text inserted.')))
		elif int(text) < 0 or int(text) > 1000000:
			runtime.manager.stack_stage(VoIPSettingNotifyStage(_('Out of range')))
		else:
			#check_voip_change(vdci_setting.ctbw, text)
			#vdci_setting.set_ctbw(text)
			setting.set_video_bitrate(int(text))
			#def register_again():
			if runtime.vdciapp:
				runtime.vdciapp.send_mesg(code1=config.MESG_SET_PARAMS, \
					code2=config.MESG_SET_VIDEO_BITRATE, mesg1=int(text))
			#runtime.manager.change_stage(phonesetting.AutoRegisteringStage)			
			runtime.manager.change_stage(NotifyStage(_('CTBW set')))
			
	def ctbw_cb(self, ui):
		text = ui.get_text()
		if len(text) == 0:
			runtime.manager.stack_stage(VoIPSettingNotifyStage(_('No text inserted.')))
		elif int(text) < 80 or int(text) > 800:
			runtime.manager.stack_stage(VoIPSettingNotifyStage(_('Out of range')))
		else:
			check_voip_change(vdci_setting.ctbw, text)
			vdci_setting.set_ctbw(text)
			def register_again():
				runtime.manager.change_stage(phonesetting.AutoRegisteringStage)			
			runtime.manager.change_stage(VoIPSettingNotifyStage(_('CTBW set'), register_again))

			

			

class VideoCodecPriority(ListStage):
	domonitor_forbidden = True
	def __init__(self):
		self.title = _('VIDEO CODEC PRIORITY')
		self.choice_item_index = [_('First'), _('Second'), _('Third')]
		self.choice_index = ['H. 264', 'H. 263', 'MPEG4', _('None')]
		self.count = 0
		self.choice = []
		self.cntNotNone = 0		# by shchun: None을 제외한 설치된codec 개수 
		for i in setting.video_codec_selected_index:
			self.choice.append(str(self.choice_item_index[self.count] + ' - '+ self.choice_index[int(setting.video_codec_selected_index[self.count])]))
			self.count=self.count+1
		ListStage.__init__(self, self.choice, right = _('SAVE'))	
		
	def activate(self, index):
		runtime.manager.stack_stage(VideoCodecList(index, self.cntNotNone)) # by shchun:

	def show(self):
		self.count = 0
		self.choice = []
		self.cntNotNone = 0
		for i in setting.video_codec_selected_index:
			# start Hyo
			#print 'setting.video_codec_selected_index[self.count]', setting.video_codec_selected_index[self.count]
			if (int(setting.video_codec_selected_index[self.count]) != 2):
				self.cntNotNone += 1
			# end Hyo
			self.choice.append(str(self.choice_item_index[self.count] + ' - '+ self.choice_index[int(setting.video_codec_selected_index[self.count])]))
			self.count=self.count+1
		ListStage.change_choice(self, self.choice)
		ListStage.show(self)
		
	def handle_key(self, key):
		if  key == config.Menu2:
			runtime.manager.back_stage()
			def register_again():
				runtime.manager.change_stage(phonesetting.AutoRegisteringStage)
			runtime.manager.stack_stage(VoIPSettingNotifyStage(_('Video codec priority set'), register_again))
		else:
			return ListStage.handle_key(self, key)	


class AudioCodecPriority(ListStage):
	domonitor_forbidden = True
	def __init__(self):
		self.title = _('AUDIO CODEC PRIORITY')
		#self.choice_item_index = [_('First'), _('Second'), _('Third'), _('Fourth'), _('Fifth'), _('Sixth')]
		#self.choice_index = [_('G.711 ulaw'), _('G.711 alaw'), _('G.723'), _('G.729'), _('AMR'), _('G.722'), _('None')]
		self.choice_item_index = [_('First'), _('Second'), _('Third'), _('Fourth'), _('Fifth'), _('Sixth')]
		self.choice_index = [('G.722'), _('G.711 alaw'), _('G.711 ulaw'), _('G.729'), _('None')]
		self.count = 0
		self.choice = []
		self.cntNotNone = 0		# by shchun: None을 제외한 설치된codec 개수 self.audio_codec_selected_index = ['0','1','11','2','11','12']

		for i in setting.audio_codec_selected_index: # 1 2 3 6
			#print 'ka.........int(setting.audio_codec_selected_index[self.count])=', int(setting.audio_codec_selected_index[self.count])
			#print 'ka...choice = ', self.choice_index[int(setting.audio_codec_selected_index[self.count])]
		
			self.choice.append(str(self.choice_item_index[self.count] + ' - '+ self.choice_index[int(setting.audio_codec_selected_index[self.count])]))
			self.count=self.count+1
		ListStage.__init__(self, self.choice, right = _('SAVE'))	
		
	def activate(self, index):
		runtime.manager.stack_stage(AudioCodecList(index, self.cntNotNone))
		
	def show(self):
		self.count = 0
		self.choice = []
		self.cntNotNone = 0
		for i in setting.audio_codec_selected_index:
			
			# start Hyo
			#print 'setting.audio_codec_selected_index[self.count]', setting.audio_codec_selected_index[self.count]
			if (int(setting.audio_codec_selected_index[self.count]) != 6): # index 6 == None
				self.cntNotNone += 1
			# end Hyo
			self.choice.append(str(self.choice_item_index[self.count] + ' - '+ self.choice_index[int(setting.audio_codec_selected_index[self.count])]))
			self.count=self.count+1
		ListStage.change_choice(self, self.choice)
		ListStage.show(self)
		

	# vpark 2007.01.19 Setting G.711 ulaw as default if not selected
	def handle_key(self, key):
		'''
		if key == config.Menu4 or key == config.Red:				
			if config.default_audio_codec not in setting.audio_codec_selected: # check if default codec is not in list
				setting.audio_codec_list_index.sort()
				setting.audio_codec_selected_index.pop(setting.audio_codec_selected_index.index(config.codec_index_value_for_None)) # remove None
				# remove default codec from available list and add default codec at last
				setting.audio_codec_selected_index.insert(int(config.audio_codec_num), setting.audio_codec_list_index.pop(0)) 
				# for vdci.cfg
				setting.audio_codec_selected = []
				count_index=0
				count_none=0
				count_list = 0
				for i in setting.audio_codec_selected_index:
					if setting.audio_codec_selected_index[count_index] != config.audio_codec_num:
						setting.audio_codec_selected.insert(count_list, config.audio_codec_list[int(setting.audio_codec_selected_index[count_index])])
						count_list = count_list+1
					else:
						count_none=count_none+1
					count_index=count_index+1

				# filling out the rest
				for i in range(count_none+int(config.max_codec_num)-int(config.audio_codec_num)):
					setting.audio_codec_selected.append(config.audio_codec_list[int(config.audio_codec_num)])

				audio_codec = ''
				count_index = 0
				for i in setting.audio_codec_selected:
					audio_codec = audio_codec + setting.audio_codec_selected[count_index]
					if count_index < int(config.max_codec_num)-1:
						audio_codec = audio_codec + ':'
					count_index = count_index + 1

				check_voip_change(vdci_setting.audio_codec, audio_codec)
				vdci_setting.set_audio_codec(audio_codec)
				runtime.manager.back_stage()
				runtime.manager.stack_stage(VoIPSettingNotifyStage(_('G.711 ulaw added to the list as default.')))
				return True
		
			else:
				return ListStage.handle_key(self, key)
		'''
		if  key == config.Menu2:
			runtime.manager.back_stage()
			def register_again():
				runtime.manager.change_stage(phonesetting.AutoRegisteringStage)
			runtime.manager.stack_stage(VoIPSettingNotifyStage(_('Audio codec priority set'), register_again))		
		else:
			return ListStage.handle_key(self, key)
	
class AudioCodecList(ListStage):
	def __init__(self, priority, cntNotNone = 0):
		#print 'ka.....priority=', priority
		#print 'ka....cntNotNone=', cntNotNone
		self.priority = priority
		title_choice = (_('FIRST'), _('SECOND'), _('THIRD'), _('FOURTH'), _('FIFTH'), _('SIXTH'))
		#self.choice_index = [(_('G.711 ulaw'),), (_('G.711 alaw'),), (_('G.723'),), (_('G.729'),), (_('AMR'),), (_('G.722'),), (_('None'),)]		
		self.choice_index = [(_('G.722'),),( _('G.711 alaw'),), (_('G.711 ulaw'),), (_('G.729'),), (_('None'),)]

		self.title = title_choice[priority]+  ' - ' + self.choice_index[int(setting.audio_codec_selected_index[priority])][0]
		
		self.choice = ()
		self.count = 0
		setting.audio_codec_list_index.sort()
		#print '###setting.audio_codec_list_index=', setting.audio_codec_list_index
		for i in setting.audio_codec_list_index:
			self.choice = self.choice + tuple(self.choice_index[int(setting.audio_codec_list_index[self.count])])
			self.count=self.count+1
		if cntNotNone > 1:
			self.choice = self.choice + tuple(self.choice_index[int(config.audio_codec_num)])
		ListStage.__init__(self, self.choice)

	def activate(self,index):
		if index != self.count:
			codec_selected_index_tmp = setting.audio_codec_selected_index.pop(self.priority)
			if codec_selected_index_tmp != config.audio_codec_num:
				setting.audio_codec_list_index.append(codec_selected_index_tmp)
			codec_list_index_tmp = setting.audio_codec_list_index.pop(index)
			if codec_list_index_tmp != config.audio_codec_num:
				setting.audio_codec_selected_index.insert(self.priority, codec_list_index_tmp)
		else:
			if setting.audio_codec_selected_index[self.priority] != config.audio_codec_num:
				codec_selected_index_tmp = setting.audio_codec_selected_index.pop(self.priority)
				setting.audio_codec_list_index.append(codec_selected_index_tmp)
				setting.audio_codec_selected_index.insert(self.priority, config.audio_codec_num)

		setting.audio_codec_selected = []
		count_index=0
		count_none=0
		count_list = 0
		# test
		for i in setting.audio_codec_selected_index:
			setting.audio_codec_selected.insert(count_list, config.audio_codec_list[int(setting.audio_codec_selected_index[count_index])])
			count_index=count_index+1
		# for vdci.cfg
		setting.audio_codec_selected = []
		count_index=0
		count_none=0
		count_list = 0
		for i in setting.audio_codec_selected_index:
			if setting.audio_codec_selected_index[count_index] != config.audio_codec_num:
				setting.audio_codec_selected.insert(count_list, config.audio_codec_list[int(setting.audio_codec_selected_index[count_index])])
				count_list = count_list+1
			else:
				count_none=count_none+1
			count_index=count_index+1

		# filling out the rest
		for i in range(count_none+int(config.max_codec_num)-int(config.audio_codec_num)):
			setting.audio_codec_selected.append(config.audio_codec_list[int(config.audio_codec_num)])

		audio_codec = ''
		count_index = 0
		for i in setting.audio_codec_selected:
			audio_codec = audio_codec + setting.audio_codec_selected[count_index]
			if count_index < int(config.max_codec_num)-1:
				audio_codec = audio_codec + ':'
			count_index = count_index + 1

		#print 'ka.....................audio_codec=', vdci_setting.audio_codec
		#print 'ka..................22audio_codec=', audio_codec
		check_voip_change(vdci_setting.audio_codec, audio_codec)
		vdci_setting.set_audio_codec(audio_codec)
		
		
		#print setting.audio_codec_list_index
		#print setting.audio_codec_selected_index
		#print setting.audio_codec_selected
		
		runtime.manager.back_stage()
		#def register_again():
		#	runtime.manager.change_stage(phonesetting.AutoRegisteringStage)
		#runtime.manager.stack_stage(VoIPSettingNotifyStage(_('Audio codec priority set'), register_again))
		

class VideoCodecList(ListStage):
	def __init__(self, priority, cntNotNone=0):
		self.priority = priority
		title_choice = (_('FIRST'), _('SECOND'),  _('THIRD'))
		self.choice_index = [('H. 264',), ('H. 263',) , ('MPEG4',), (_('None'),)]
		#print '### int(setting.video_codec_selected_index[priority])', int(setting.video_codec_selected_index[priority])
		self.title = title_choice[priority]+  ' - ' + self.choice_index[int(setting.video_codec_selected_index[priority])][0]
		
		self.choice = ()
		self.count = 0
		setting.video_codec_list_index.sort()
		#print setting.video_codec_list_index
		for i in setting.video_codec_list_index:
			self.choice = self.choice + tuple(self.choice_index[int(setting.video_codec_list_index[self.count])])
			self.count=self.count+1
			
		if cntNotNone > 1:
			self.choice = self.choice + tuple(self.choice_index[int(config.video_codec_num)])
		ListStage.__init__(self, self.choice)

	def activate(self,index):
		if index != self.count:
			codec_selected_index_tmp = setting.video_codec_selected_index.pop(self.priority)
			if codec_selected_index_tmp != config.video_codec_num:
				setting.video_codec_list_index.append(codec_selected_index_tmp)
			codec_list_index_tmp = setting.video_codec_list_index.pop(index)
			if codec_list_index_tmp != config.video_codec_num:
				setting.video_codec_selected_index.insert(self.priority, codec_list_index_tmp)
		else:
			if setting.video_codec_selected_index[self.priority] != config.video_codec_num:
				codec_selected_index_tmp = setting.video_codec_selected_index.pop(self.priority)
				setting.video_codec_list_index.append(codec_selected_index_tmp)
				setting.video_codec_selected_index.insert(self.priority, config.video_codec_num)

		setting.video_codec_selected = []
		count_index=0
		count_none=0
		count_list = 0
		# test
		for i in setting.video_codec_selected_index:
			setting.video_codec_selected.insert(count_list, config.video_codec_list[int(setting.video_codec_selected_index[count_index])])
			count_index=count_index+1
		# for vdci.cfg
		setting.video_codec_selected = []
		count_index=0
		count_none=0
		count_list = 0
		for i in setting.video_codec_selected_index:
			if setting.video_codec_selected_index[count_index] != config.video_codec_num:
				setting.video_codec_selected.insert(count_list, config.video_codec_list[int(setting.video_codec_selected_index[count_index])])
				count_list = count_list+1
			else:
				count_none=count_none+1
			count_index=count_index+1

		# filling out the rest
		for i in range(count_none+int(config.max_codec_num)-int(config.video_codec_num)):
			setting.video_codec_selected.append(config.audio_codec_list[int(config.audio_codec_num)])

		video_codec = ''
		count_index = 0
		for i in setting.video_codec_selected:
			video_codec = video_codec + setting.video_codec_selected[count_index]
			if count_index < int(config.max_codec_num)-1:
				video_codec = video_codec + ':'
			count_index = count_index + 1
		

		check_voip_change(vdci_setting.video_codec, video_codec)
		vdci_setting.set_video_codec(video_codec)
		
		#print setting.video_codec_list_index
		#print setting.video_codec_selected_index
		#print setting.video_codec_selected
		runtime.manager.back_stage()
		#def register_again():			
		#	runtime.manager.change_stage(phonesetting.AutoRegisteringStage)
		#runtime.manager.stack_stage(VoIPSettingNotifyStage(_('Video codec priority set'), register_again))
# KA: [20071006] TI IMS Codec Priority ==


class Misc(ListStage):
	icon = uiconfig.setting_voip_icon

	#/usr/etc/miscmenu_on 파일이 존재할때만 packets 메뉴보임
	def __init__(self):

		self.title = _('MISC.')
		self.choice1 = (_('Domain name'), _('MTU'), _('CTBW'), _('Ports'),  _('Codec priority'))
		self.choice2 = (_('Domain name'), _('MTU'), _('CTBW'), _('Ports'), _('Packets'))
		self.choice_normal = (_('CTBW'),)
		self.choice_PSTN = (_('Domain name'))

		if status.debug_mode:
			self.packets_on = self.check_packetmenu_on()
			if self.packets_on:
				self.choice = self.choice2
			else:
				self.choice = self.choice1
		else:
			self.choice = self.choice_normal

		ListStage.__init__(self, self.choice, self.title, self.icon)

	def activate(self, index):
		if self.choice[index] == _('Domain name'):
			domain = vdci_setting.domain
			stage = VoIPEditor(_('DOMAIN NAME'), _('Domain name'), self.domain_cb, text=domain, textmax = 50, ischr=True)

		elif self.choice[index] == _('MTU'):
			mtu = vdci_setting.mtu
			stage = VoIPEditor(_('MTU'), _('MTU (50~1500)'), self.mtu_cb, text=str(mtu), textmax = 4, only_num = 2)

		elif self.choice[index] == _('CTBW'):
			ctbw = vdci_setting.ctbw
			stage = VoIPEditor(_('CTBW'), _('CTBW (40~500)'), self.ctbw_cb, text=str(ctbw), textmax = 3, only_num = 2)

		elif self.choice[index] == _('Ports'): # Ports
			stage = Ports

		elif self.choice[index] == _('Packets'):# Packets
			stage = Packets
			
		elif self.choice[index] == _('Codec priority'):
			stage = CodecPriority

		runtime.manager.stack_stage(stage)

	def check_packetmenu_on(self):
		# miscmenu_on이 있는 경우만 misc메뉴보임
		if os.path.exists('/usr/etc/packet_on'):
			return True
		else:
			return False

	def domain_cb(self, ui):
		text = ui.get_text()
		if len(text) == 0:
			runtime.manager.stack_stage(VoIPSettingNotifyStage(_('No text inserted.')))
		else:
			check_voip_change(vdci_setting.domain, text)
			vdci_setting.set_domain(text)
			runtime.manager.change_stage(VoIPSettingNotifyStage(_('Domain name set')))

	def mtu_cb(self, ui):
		text = ui.get_text()
		if len(text) == 0:
			runtime.manager.stack_stage(VoIPSettingNotifyStage(_('No text inserted.')))
		elif int(text) < 50 or int(text) > 1500:
			runtime.manager.stack_stage(VoIPSettingNotifyStage(_('Out of range')))
		else:
			check_voip_change(vdci_setting.mtu, text)
			vdci_setting.set_mtu(text)
			runtime.manager.change_stage(VoIPSettingNotifyStage(_('MTU set')))

	def ctbw_cb(self, ui):
		text = ui.get_text()
		if len(text) == 0:
			runtime.manager.stack_stage(VoIPSettingNotifyStage(_('No text inserted.')))
		elif int(text) < 40 or int(text) > 500:
			runtime.manager.stack_stage(VoIPSettingNotifyStage(_('Out of range')))
		else:
			check_voip_change(vdci_setting.ctbw, text)
			vdci_setting.set_ctbw(text)
			runtime.manager.change_stage(VoIPSettingNotifyStage(_('CTBW set')))

class DevMisc(ListStage):
	def __init__(self):
		self.title = _('DEV_MISC')
		self.choice = (_('ITSP Support'), _('MTU'), _('CTBW'), _('NAT Timer'), _('Reg Interval'), _('IFCONFIG'), _('Telnetd'), _('Calculator in C++'), 'AniImages')
		ListStage.__init__(self, self.choice, self.title)
	
	def activate(self, index):
		stage = None

		print '### self.choice[index] ', self.choice[index],  _('Domain name')
		if self.choice[index] == _('Domain name'):
			domain = vdci_setting.domain
			stage = VoIPEditor(_('DOMAIN NAME'), _('Domain name'), self.domain_cb, text=domain, textmax = 50, ischr=True)

		elif self.choice[index] == _('MTU'):
			mtu = vdci_setting.mtu
			stage = VoIPEditor(_('MTU'), _('MTU (50~1500)'), self.mtu_cb, text=str(mtu), textmax = 4, only_num = 2)

		elif self.choice[index] == _('CTBW'):
			ctbw = vdci_setting.ctbw
			stage = VoIPEditor(_('CTBW'), _('CTBW (40~500)'), self.ctbw_cb, text=str(ctbw), textmax = 3, only_num = 2)

		elif self.choice[index] == _('Ports'): # Ports
			stage = Ports

		elif self.choice[index] == _('Packets'):# Packets
			stage = Packets
			
		elif self.choice[index] == _('Codec priority'):
			stage = CodecPriority
		elif self.choice[index] == _('ITSP Support'):
			itsp = vdci_setting.itsp_support
			stage = VoIPEditor(_('ITSP Support'), _('ITSP (0~20)'), self.itsp_cb, text=str(itsp), textmax = 2, only_num = 2)
		elif self.choice[index] == _('NAT Timer'):
			nat_timer = vdci_setting.nat_timer
			stage = VoIPEditor(_('NAT TIMER'), _('NAT TIMER (0~999), disable==0'), self.nat_timer_cb, text=str(nat_timer), textmax = 3, only_num = 2)
		elif self.choice[index] ==  _('Reg Interval'):
			nat_timer = vdci_setting.expires
			stage = VoIPEditor(_('REG EXPIRES'), _('Register interval (60~99999)'), self.expires_cb, text=str(nat_timer), textmax = 5, only_num = 2)

		elif self.choice[index] == _('IFCONFIG'):
			#default_ipaddress='192.168.10.1'
			default_ipaddress='150.150.141.101'
			stage = VoIPEditor(_('IFCONFIG'), _('ipaddress'), self.ifconfig_cb, text=str(default_ipaddress), textmax = 16)

		elif self.choice[index] == _('Telnetd'):
			stage = TelnetdStage

		elif self.choice[index] == _('Calculator in C++'):
			stage = CalcCStage
		elif self.choice[index] == 'AniImages':
			stage = AniImagesStage
		if stage:
			runtime.manager.stack_stage(stage)


	def check_packetmenu_on(self):
		# miscmenu_on이 있는 경우만 misc메뉴보임
		if os.path.exists('/usr/etc/packet_on'):
			return True
		else:
			return False

	def domain_cb(self, ui):
		text = ui.get_text()
		if len(text) == 0:
			runtime.manager.stack_stage(VoIPSettingNotifyStage(_('No text inserted.')))
		else:
			check_voip_change(vdci_setting.domain, text)
			vdci_setting.set_domain(text)
			runtime.manager.change_stage(VoIPSettingNotifyStage(_('Domain name set')))

	def mtu_cb(self, ui):
		text = ui.get_text()
		if len(text) == 0:
			runtime.manager.stack_stage(VoIPSettingNotifyStage(_('No text inserted.')))
		elif int(text) < 50 or int(text) > 1500:
			runtime.manager.stack_stage(VoIPSettingNotifyStage(_('Out of range')))
		else:
			check_voip_change(vdci_setting.mtu, text)
			vdci_setting.set_mtu(text)
			runtime.manager.change_stage(VoIPSettingNotifyStage(_('MTU set')))

	def ctbw_cb(self, ui):
		text = ui.get_text()
		if len(text) == 0:
			runtime.manager.stack_stage(VoIPSettingNotifyStage(_('No text inserted.')))
		elif int(text) < 40 or int(text) > 500:
			runtime.manager.stack_stage(VoIPSettingNotifyStage(_('Out of range')))
		else:
			check_voip_change(vdci_setting.ctbw, text)
			vdci_setting.set_ctbw(text)
			runtime.manager.change_stage(VoIPSettingNotifyStage(_('CTBW set')))

	def itsp_cb(self, ui):
		text = ui.get_text()
		if len(text) == 0:
			runtime.manager.stack_stage(VoIPSettingNotifyStage(_('No text inserted.')))
		elif int(text) < 0 or int(text) > 20:
			runtime.manager.stack_stage(VoIPSettingNotifyStage(_('Out of range')))
		else:
			check_voip_change(vdci_setting.itsp_support, text)
			vdci_setting.set_itsp(text)
			runtime.manager.change_stage(VoIPSettingNotifyStage(_('ITSP support set')))

	def nat_timer_cb(self, ui):
		text = ui.get_text()
		if len(text) == 0:
			runtime.manager.stack_stage(VoIPSettingNotifyStage(_('No text inserted.')))
		elif int(text) < 0:
			runtime.manager.stack_stage(VoIPSettingNotifyStage(_('Out of range')))
		else:
			check_voip_change(vdci_setting.nat_timer, text)
			vdci_setting.set_nat_timer(text)
			runtime.manager.change_stage(VoIPSettingNotifyStage(_('NAT Timer set')))		

	def expires_cb(self, ui):
		text = ui.get_text()
		if len(text) == 0:
			runtime.manager.stack_stage(VoIPSettingNotifyStage(_('No text inserted.')))
		elif int(text) < 60:
			runtime.manager.stack_stage(VoIPSettingNotifyStage(_('Out of range')))
		else:
			check_voip_change(vdci_setting.expires, text)
			vdci_setting.set_expires(text)
			runtime.manager.change_stage(VoIPSettingNotifyStage(_('Reg Timer set')))	

	def ifconfig_cb(self, ui):
		text = ui.get_text()
		if len(text) == 0:
			runtime.manager.stack_stage(VoIPSettingNotifyStage(_('No text inserted.')))
		else:
			str='/sbin/ifconfig eth0 %s up'%text
			print 'run str=', str
			os.system(str)
			runtime.manager.change_stage(VoIPSettingNotifyStage(_('ifconfig up!!')))

class AniImagesStage(Stage):
	
	name = 'Ani image'
	def __init__(self):
		self.title ='Ani Images test'
		self.ui = baseui.BaseUI('OK','',self.title,'','BACK')
		self.ani = runtime.evas.aniimages(pos=(0,0), files=uiconfig.incoming_call_ani)
		self.ui.add(self.ani)
		
	def handle_key(self, key):
		# filter keys first before passing to ui
		if key == config.Menu4 or key == 'CLR':
			runtime.manager.back_stage()
			return True

class CalcCStage(Stage):
	title = _('CALCULATOR')
	name = 'Calculator'
	def __init__(self):
		# in this example, the title, background and menu are drawn from python using baseui
		self.ui = baseui.BaseUI('OK','AC',self.title,'CLR','BACK')
		# this example calculator widget will be drawn in to the python stage
		self.calc = runtime.evas.widgetExample();
		self.ui.add(self.calc)
		# install key hander in the python environment and pass through
		#  keys back to C++ to the widget
		#import PythonQt
		#self.ca = QCalendarWidget()
		#self.ui.add(self.ca)
		
		self.tmpkey = runtime.evas.handle_key;
		runtime.evas.handle_key = self.handle_key

	def handle_key(self, down, key):
		# filter keys first before passing to ui
		if key == config.Menu4 or key == 'CLR':
			# Can add any extra key filtering for system events here
			runtime.manager.back_stage()
			return True
		else:
			# send key to the ui
			return self.calc.handle_key(down, key)

	def destroy(self):
		# uninstall the keyboard handler and cleanup
		runtime.evas.handle_key = self.tmpkey;
		self.ui.destroy()

#start shchun : en/disable inetd
class TelnetdStage(YesNoStage):
	def __init__(self):
		self.isalive = self.is_telnetd_alive()
		
		print 'self.isalive', self.isalive
		if self.isalive:
			message = _('Telnet/Ftp enabled.')+'\n'+_('Disable?')
		else:
			message = _('Telnet/Ftp disabled.')+'\n'+_('Enable?')
		
		icon = uiconfig.baloon_phone_setting_icon
		YesNoStage.__init__(self, message, self.yes_cb, runtime.manager.back_stage, '', icon)
	def yes_cb(self):
		if self.isalive:
			os.system('killall telnetd')
			debugLogC('IPT_START - TelnetFtpStage')
			os.system('/usr/local/bin/ipt_start')

			#from vdcisetting import vdci_setting
			#vdci_setting.set_ip_filter_enable('yes')
			stage = VoIPSettingNotifyStage(_('Telnet/Ftp disabled.'))
		else:
			os.system('telnetd &')
			
			debugLogC('IPT_STOP - TelnetFtpStage')
			os.system('/usr/local/bin/ipt_stop')
			
			#from vdcisetting import vdci_setting
			#vdci_setting.set_ip_filter_enable('no')
			stage = VoIPSettingNotifyStage(_('Telnet/Ftp enabled.'))
			
		runtime.manager.change_stage(stage)
			
	def is_telnetd_alive(self):
		try:
			os.system('ps -ae|  grep -v grep | grep telnetd > /tmp/_telnetd_check')
			fp = open('/tmp/_telnetd_check')
			t=fp.read()
			fp.close()

			run_proc = t.count('telnetd')
		except:
			print 'is_inetd_alive: exception'
			return False
		if run_proc == 0:
			return False
		else:
			return True
# end shchun
	
class SystemSettingStage(ListStage):
	name = 'system setting'
	icon = uiconfig.setting_system_icon
	def __init__(self):
		self.title = _('SYSTEM SETTINGS')

		import profile
		self.c_prf = profile.profile.get_profile()
		if self.c_prf == 0:
			self.choice = (_('Date and time'),	_('Bluetooth'),	_('PIN'), _('Technical features'), _('Reset'))
		elif self.c_prf == 1:
#ka...malaga 2007.04.10
#			self.choice = (_('Date and time'), _('Network time'), _('LAN'), _('Bluetooth'),	_('PIN'), _('Technical features'), _('Reset'))
			self.choice = (_('Date and time'), _('Network time'), _('LAN'), _('PIN'), _('Technical features'), _('Reset'), _('DECT registration'), _('DECT reset'), _('DECT Functions'))
		else: # wifi
#ka...malaga 2007.04.10
#			self.choice = (_('Date and time'), _('Network time'), _('WiFi'), _('Bluetooth'),	_('PIN'), _('Technical features'), _('Reset'))
			self.choice = (_('Date and time'), _('Network time'), _('WiFi'), _('PIN'), _('Technical features'), _('Reset'), 	_('DECT registration'), _('DECT reset'), _('DECT Functions'))

		ListStage.__init__(self, choice=self.choice, title=self.title)
	def activate(self, index):
		stage = phonesetting.get_stage_system(self.c_prf, index)
		runtime.manager.stack_stage(stage)

class SettingStage(ListStage):
	name= 'setting stage'  # shchun : add name 
	#titleimage = uiconfig.title_setting
	icon = uiconfig.phone_setting_icon
	index = 0
	def __init__(self):
		self.title = _('SETTINGS')
		self.choice = (_('Incomingcall barring'), _('Handy setting'),_('Password setting'), _('Phone infomation'), _('Network settings'), _('Phone reset'), _('Language setting'),_('Timezone setting'))
		ListStage.__init__(self, choice=self.choice, title=self.title)

	def show(self):
		ListStage.show(self)
		#self.ui.set_focus(self.index)

	def activate(self, index):
		if config.KT_500:
			if index in (3, 4):
				if index == 3:	
					mode = 4
				elif index == 4:	
					mode = 5
				self.ui.set_focus(index) #QE-28436
				stage = CheckPasswordStage(mode)
				runtime.manager.stack_stage(stage)
				return
		else:
			if index in (1, 4, 5):
				if index == 1:		
					mode = 3
				elif index == 4:	
					mode = 4
				elif index == 5:	
					mode = 5
				self.ui.set_focus(index) #QE-28436				
				stage = CheckPasswordStage(mode)
				runtime.manager.stack_stage(stage)
				return
				
		self.index = index
		
#		stage = (CallSettingStage, DectSettingStage, PasswordSettingStage, phonesetting.PhoneInformationStage, \
#						newprof.ProfileListStage, phonesetting.ProfileStage,  \
#						phonesetting.LanguageStage, NetworkEVStage)[index]
		stage = (phonesetting.IncomingRestrictStage, DectSettingStage, PasswordSettingStage, phonesetting.PhoneInformationStage, \
						newprof.ProfileListStage, phonesetting.ProfileStage,  \
						phonesetting.LanguageStage, TimeZoneSettingStage, NetworkEVStage)[index]
						

		#print 'WARNING: for debug I located phonesetting.ProfileStage to Reset position..
		runtime.manager.stack_stage(stage)


class NetworkEVStage(Stage):
	def __init__(self):
		if setting.video_bitrate == 0:
			index = 0
		else:
			index = 1
		choice = (_('High speed internet'), 'ADSL')
		self.ui = baseui.OneSelectBoxUI(index, _('SAVE'), '', '', _('BACK'), choice)
		
	def registering(self):	
		stage = phonesetting.AutoRegisteringStage
		runtime.manager.change_stage(stage, True)
		
	def save(self):
		if self.ui.list.index == 0:
			setting.set_video_bitrate(0)
			codec ='12:1:0:3:11:11' 
			codec_list = ['0','1','2','3']
		elif self.ui.list.index == 1:
			setting.set_video_bitrate(128000)
			codec = '3:12:1:0:11:11'
			codec_list = ['3','0','1','2']
			
		setting.set_audio_codec(codec_list)	
		vdci_setting.set_audio_codec(codec)

		stage = NotifyStage(message=_('Applying system'), cb=self.registering)
		utils.player.play_effect(config.SETTING_SUCCEEDED)
		runtime.manager.change_stage(stage)	
		
	def handle_key(self,key):
		if key == config.Menu1 or key == 'OK':
			self.save()
		elif key == config.Menu4 or key == 'CLR':				
			runtime.manager.back_stage()
		else:
			self.ui.handle_key(key)

	
class CallSettingStage(ListStage):
	icon = uiconfig.call_setting_icon
	#titleimage = uiconfig.title_call_setting
	name = 'call setting'
	index =0
	
	def __init__(self):
		self.title = _('CALL SETTINGS')
		self.choice = (_('Outgoing restrict'), _('Incoming restrict') )

		ListStage.__init__(self, choice=self.choice, title=self.title, icon=self.icon)

	def show(self):
		ListStage.show(self)
		self.ui.set_focus(self.index)

	def activate(self, index):
		self.index = index
		if index == 0:		stage = phonesetting.OutgoingRestrictStage
		elif index == 1:	stage = phonesetting.IncomingRestrictStage
		runtime.manager.stack_stage(stage)
		
class DectSettingStage(ListStage):
	#titleimage = uiconfig.title_dect_setting
	icon = uiconfig.dect_setting_icon
	name = 'dect setting'
	index =0

	def __init__(self):
		self.title = _('DECT SETTINGS')
		#choice = _('DECT registration'), _('DECT reset'),  _('DECT Functions')
		self.choice = _('DECT registration'), _('DECT information')

		ListStage.__init__(self, choice=self.choice, title=self.title, icon=self.icon)

	def show(self):
		ListStage.show(self)
		self.ui.set_focus(self.index)

	def activate(self, index):
		self.index = index
		if index == 0:	
			if runtime.dectCallManager.isSubscriptionFull():
				runtime.manager.stack_stage(NotifyStage(_('Can not subscribe more than 3.'), uiconfig.baloon_phonebook_icon))
			else:
				stage = phonesetting.DectSubscriptionStage
				runtime.manager.stack_stage(stage)
		elif index == 1:	
			stage = Dect_handset_Stage
			runtime.manager.stack_stage(stage)


class ImageSoundDeleteStage(ListStage):
	icon = uiconfig.image_image_sound_delete

	def __init__(self):
		self.title = _('DELETE')
		self.choice = _('Images'), _('Sounds'), _('Videos')
	
		ListStage.__init__(self)
	def activate(self, index):
		if index == 0:
			import images
			dirname, lists = images.get_image_gallery_list('taken')
			if len(lists) == 0:
				runtime.manager.stack_stage(NotifyStage(_('No taken photos'), uiconfig.baloon_photo_icon))
				return
			message = _('Delete all taken photos?')
			def yes():
				utils.remove_dir(utils.get_image_dir('taken'))
				stage = NotifyStage(_('All taken photos deleted'),uiconfig.baloon_image_delete_icon)
				runtime.manager.change_stage(stage)
			def no():
				runtime.manager.back_stage()
			stage = OkNoStage(message, yes, no, '', uiconfig.baloon_image_delete_icon)
			runtime.manager.stack_stage(stage)

		elif index == 1:
			import sounds
			dirname, lists = sounds.get_audio_gallery_list('recorded')
			if len(lists) == 0:
				stage = sounds.SoundNotifyStage(_('No recorded audios'))
				runtime.manager.stack_stage(stage)
				return
			message = _('Delete all recorded audios?')
			def yes():
				if config.mm_debug:
					print 'FIXME: delete all recorded audios!!'
				utils.remove_dir(utils.get_audio_dir('recorded'))
# eicho add 06.11.23 same as BT.
				utils.remove_dir(config.audio_amr2wav_recorded_dir)
# end.
				stage = NotifyStage(_('All recorded audios deleted'), uiconfig.baloon_sound_delete_icon)
				runtime.manager.change_stage(stage)
			def no():
				runtime.manager.back_stage()
			stage = OkNoStage(message, yes, no, '', uiconfig.baloon_sound_delete_icon)
			runtime.manager.stack_stage(stage)

		else:
			import videos
			dirname, thumb_dirname, lists = videos.get_video_gallery_list('recorded')
			if len(lists) == 0:
				runtime.manager.stack_stage(videos.VideoNotifyStage(_('No recorded videos')))
				return
			message = _('Delete all recorded videos?')
			
			def yes():
				stage = NotifyStage(_('All recorded videos deleted'), uiconfig.baloon_video_delete_icon)
				runtime.manager.change_stage(stage)
				if index == 0:
					utils.remove_dir(config.video_recorded_dir)
					utils.remove_dir(config.video_recorded_thumnail_dir)
				elif index == 1:
					utils.remove_dir(config.video_received_dir)
					utils.remove_dir(config.video_received_thumnail_dir)
				else:
					utils.remove_dir(config.video_recorded_dir)
					utils.remove_dir(config.video_received_dir)
					utils.remove_dir(config.video_recorded_thumnail_dir)
					utils.remove_dir(config.video_received_thumnail_dir)
			def no():
				runtime.manager.back_stage()
		
			stage = OkNoStage(message, yes, no, '', uiconfig.baloon_video_delete_icon)
			runtime.manager.stack_stage(stage)	

class CopyStage(ListStage):
	icon = uiconfig.image_sound_icon

	def __init__(self):
		self.title = _('COPY')
		self.choice = _('Images'), _('Sounds')#, _('Videos')
	
		ListStage.__init__(self)
		
	def activate(self, index):
		stage = (ImagesCopyStage, SoundsCopyStage, VideosCopyStage)[index]
		runtime.manager.stack_stage(stage)

class ImagesCopyStage(ListStage):
	icon = uiconfig.image_sound_icon

	def __init__(self):
		self.title = _('COPY')
		self.choice = _('Taken photos'), _('Received images')
	
		ListStage.__init__(self)

	def activate(self, index):
		if index == 0:
			runtime.manager.stack_stage(CopyToFromStage(config.image_taken_dir))
		else:
			runtime.manager.stack_stage(ImagesReceivedCopyStage)

class ImagesReceivedCopyStage(ListStage):
	icon = uiconfig.image_sound_icon
	def __init__(self):
		self.title = _('COPY')
		self.choice = _('Wallpapers'), _('Pictures')
		
		ListStage.__init__(self)

	def activate(self, index):
		if index == 0:
			runtime.manager.stack_stage(CopyToFromStage(config.image_wallpaper_dir))
		else:
			runtime.manager.stack_stage(CopyToFromStage(config.image_picture_dir))

class SoundsCopyStage(ListStage):
	icon = uiconfig.image_sound_icon

	def __init__(self):
		self.title = _('COPY')
		self.choice = _('Recorded audio'), _('Received melodies')
	
		ListStage.__init__(self)
	def activate(self, index):
		if index == 0:
			runtime.manager.stack_stage(CopyToFromStage(config.audio_recorded_dir))
		else:
			runtime.manager.stack_stage(SoundsReceivedCopyStage)

class SoundsReceivedCopyStage(ListStage):
	icon = uiconfig.image_sound_icon

	def __init__(self):
		self.title = _('COPY')
		self.choice = _('Polyphonic melodies'), _('Other melodies')
	
		ListStage.__init__(self)
	def activate(self, index):
		if index == 0:
			runtime.manager.stack_stage(CopyToFromStage(config.audio_polyphonic_dir))
		else:
			runtime.manager.stack_stage(CopyToFromStage(config.audio_other_dir))

class VideosCopyStage(ListStage):
	icon = uiconfig.image_sound_icon
	def __init__(self):
		self.title = _('COPY')
		self.choice = _('Recorded videos'), _('Received videos')
	
		ListStage.__init__(self)
	def activate(self, index):
		if index == 0:
			runtime.manager.stack_stage(CopyToFromStage(config.video_recorded_dir))
		else:
			runtime.manager.stack_stage(CopyToFromStage(config.video_received_dir))

class CopyToFromStage(ListStage):
	name = 'copystage'
	icon = uiconfig.image_sound_icon

	def __init__(self, direc):
		self.title = _('COPY')
#	choice = _('Copy from SD/MMC'), _('Copy to SD/MMC'), _('Copy from bluetooth'), _('Copy to bluetooth')
		self.choice = _('Copy from SD/MMC'), _('Copy to SD/MMC'), _('Copy from USB'), _('Copy to USB')

		self.direc = direc
		self.usb_check = False
		ListStage.__init__(self, self.choice, self.title)

	def show(self):
		try:
			self.fcount = len(os.listdir(self.direc))
		except:
			utils.make_dir(self.direc)
			self.fcount = 0

		ListStage.show(self)

	def activate(self, index):
		import sdmmc
		if index == 0:

#			os.system('mount -t vfat /dev/mmcda1 /usr/mmchd/')

			if self.fcount >= config.limit_filecount:
				runtime.manager.stack_stage(phonesetting.BluetoothSettingNotifyStage(_('Directory is full'), icon=uiconfig.baloon_sd_mmc_icon))

			elif sdmmc.inserted_sdmmc() == True:
				runtime.manager.stack_stage(sdmmc.FileSelectStage('filefromsdmmc', self.direc))
			else:
				runtime.manager.stack_stage(sdmmc.InsertWaitingSDMMCStage('filefromsdmmc', self.direc))

		elif index == 1:
			if self.fcount == 0:
				runtime.manager.stack_stage(phonesetting.BluetoothSettingNotifyStage(_('Empty'), icon=uiconfig.baloon_sd_mmc_icon))
			else:
				runtime.manager.stack_stage(sdmmc.FileSelectStage('filetosdmmc', self.direc))

		elif index == 2:
			if self.fcount >= config.limit_filecount:
				runtime.manager.stack_stage(phonesetting.BluetoothSettingNotifyStage(_('Directory is full'), icon=uiconfig.baloon_sd_mmc_icon))


			elif self.check_mount() == True:
				runtime.manager.stack_stage(sdmmc.FileSelectStage('filefromusb', self.direc))
			else:
				runtime.manager.stack_stage(phonesetting.BluetoothSettingNotifyStage(_('USB mount fail'), icon=uiconfig.baloon_sd_mmc_icon))
			#	runtime.manager.stack_stage(sdmmc.InsertWaitingSDMMCStage('filefromusb', self.direc))

		elif index == 3:
			if self.fcount == 0:
				runtime.manager.stack_stage(phonesetting.BluetoothSettingNotifyStage(_('Empty'), icon=uiconfig.baloon_sd_mmc_icon))

			elif self.check_mount() == True:
				runtime.manager.stack_stage(sdmmc.FileSelectStage('filetousb', self.direc))
			else:
				runtime.manager.stack_stage(phonesetting.BluetoothSettingNotifyStage(_('USB mount fail'), icon=uiconfig.baloon_sd_mmc_icon))

		'''
		elif index == 2:
			if self.fcount >= config.limit_filecount:
				runtime.manager.stack_stage(phonesetting.BluetoothSettingNotifyStage(_('Directory is full')))
			else:
				runtime.btapp.set_default()
				runtime.btapp.send_message('20|i')
				runtime.manager.stack_stage(phonesetting.BluetoothSearchStage(3, self.direc))

		elif index == 3:
			if self.fcount == 0:
				runtime.manager.stack_stage(phonesetting.BluetoothSettingNotifyStage(_('Empty')))
			else:
				runtime.manager.stack_stage(sdmmc.FileSelectStage('filetobluetooth', self.direc))
		'''

	def check_mount(self):
		if self.usb_check:
			return True

		import sdmmc
		if sdmmc.mount_usb():
			#print 'ka...### success USB'
			self.usb_check = True
			return True
		for i in range(100):
			if sdmmc.mount_usb():
				#print 'ka...### success USB   count=', i
				self.usb_check = True
				return True
			else:
				#print 'ka...### fail USB   count=', i
				pass

	def destory(self):
		import sdmmc
		sdmmc.umount_usb()
		ListStage.show(self)


class MultimediaStage(ListStage):
	
	icon = uiconfig.multimedia_icon
	def __init__(self):
		self.title = _('MULTIMEDIA')
		self.choice = _('Capture/Record'), _('My album'),  _('Media player')#'USB SD player'
		
		ListStage.__init__(self)

	def activate(self, index):
		if index == 0:
			import mmtools
			stage = mmtools.MMToolsStage
			runtime.manager.stack_stage(stage)
		elif index == 1:
			stage = MyAlbumStage
			runtime.manager.stack_stage(stage)
		#elif index == 2:
		#	# keytone 짤림 방지용 sleep
		#	import time
		#	time.sleep(0.3)
		#	from eaHandler import EaHandler
		#	runtime.eaHandler.startDownloadContents()
		#	#runtime.eaHandler.activateApplication(destination=EaHandler.MULTIMEDIA)
		elif index == 2:
			# keytone 짤림 방지용 sleep
			import time
			time.sleep(0.3)
			from eaHandler import EaHandler
			runtime.eaHandler.startMediaPlayer()
			#runtime.eaHandler.activateApplication(destination=EaHandler.MULTIMEDIA)
		elif index == 3:
			import sdmmc
			stage = sdmmc.PlayingFromStage
			runtime.manager.stack_stage(stage)

	
class SelectExternalAlbumStage(ListStage):
	name = 'select external album'
		
	icon=uiconfig.ico_mm_ext_myalbum
	#titleimage=uiconfig.Third_title_mm_ext_myalbum

	def __init__(self):
		self.title = _('SELECT EXTERNAL ALBUM')
		self.choice = _('SD/MMC'),  _('USB')

		ListStage.__init__(self)
	
	def activate (self, index):
		
		if index == 0:	
			import images
			stage = images.ExternalPhotoGalleryListStage('sdmmc')
		elif index == 1:
			import images
			stage = images.ExternalPhotoGalleryListStage('usb')
		else:
			return
		runtime.manager.stack_stage(stage)
		return


class MyAlbumStage(ListStage):
	name = 'my album'
	icon=uiconfig.ico_mm_myalbum
	#titleimage=uiconfig.Third_title_mm_myalbum
	
	def __init__(self):
		self.title = _('MY ALBUM')
		self.choice = _('Photo album'), _('Video album'), _('Voice album'), _('Copy from External Memory')

		ListStage.__init__(self)
		
	def activate (self, index):
		if index == 0:
			import images
			#stage = images.PhotoGalleryStage('taken')
			stage = images.PhotoGalleryListStage('taken')
			'''
			import images
			stage = images.ExternalPhotoGalleryListStage('sdmmc')
			'''
		elif index == 1:
			import videos
			stage = videos.VideoGalleryStage('recorded')
		elif index == 2:
			import sounds
			stage = sounds.AudioGalleryStage('recorded')
		elif index == 3:
			stage = SelectExternalAlbumStage()
		runtime.manager.stack_stage(stage)
		return


class DownloadedContentStage(ListStage):
	def __init__(self):
		self.title = _('DOWNLOADED CONTENTS')
		self.choice = _('Bell'), _('Background')

		ListStage.__init__(self)
	def activate (self, index):
		return


class KtTestStage(ListStage):
	titleimage = uiconfig.title_imagesound
	icon = uiconfig.image_sound_icon
	
	def __init__(self):
		self.title = _('KtTestStage')
		self.choice = _('Basic call'),_('call'), _('SMS'), 'MMS http server', 'Phonebook sync server'

		ListStage.__init__(self, self.choice, self.title)

	def activate(self,index):
		if index == 0:
			stage = BasicCallTestStage
		elif index == 1:
			stage = CallTestStage
		elif index == 2:
			stage = SmsTestStage
		elif  index == 3:
			stage = ServerSetstage(case=0)		
		elif index == 4:
			stage = ServerSetstage(case=1)
		elif index == 5:
			stage = EtcStage
		runtime.manager.stack_stage (stage)
		return

		
	def handle_key (self, key):
		ret = ListStage.handle_key(self,key)
		if key == config.Menu2:
			from model import MenuStage
			
			runtime.manager.stack_stage(MenuStage)
			return True
		return ret
		
class ServerSetstage(Stage):
	def __init__(self, case=0):
		self.case = case
		if case == 0:
			subtitle = 'MMS HTTP SERVER'
			value = setting.mms_http_server
		elif case == 1:
			subtitle = 'PHONEBOOK SYNC SERVER'
			from syncHandler import sync
			value = sync.get_sync_server()			
		self.ui = ui.NormalDigitEditUI('', 'Direct IP call', subtitle, 50)
		self.ui.set_text(value)

	def save(self):
		text = self.ui.get_text()
		if len(text) == 0:
			runtime.manager.stack_stage(NotifyStage(_('No text inserted.')))
			return		
		if self.case == 0:
			setting.set_mms_server(text.strip())
			runtime.manager.change_stage(NotifyStage(_('Please reboot for apply')))
		elif self.case == 1:
			from syncHandler import sync
			sync.set_sync_server(text.strip())
			runtime.manager.change_stage(NotifyStage(_('SYNC server set')))
	

	def handle_key(self, key):
		if key in ('OK', config.Menu1):
			self.save()
			return True
		else:
			return self.ui.handle_key(key)
			
	def destroy(self):
		Stage.destroy(self)


class VoiceQualityTestStage(ListStage):

	def __init__(self):
		self.title = 'Voice Quality Test'

		if os.access("/usr/etc/testmodeVQ", os.F_OK):
			self.voice_qulity_test_flag = True
		else:
			self.voice_qulity_test_flag = False
			
		if self.voice_qulity_test_flag == True:
			self.choice = 'Disable',
		else:
			self.choice = 'Enable',
		ListStage.__init__(self, choice=self.choice)
		
	def set_network(self):
		os.system('cp /usr/etc/ethernet.cfg  /usr/etc/ethernet.cfg.BAK')
		os.system('cp /usr/etc/ethernet.cfg.VQ  /usr/etc/ethernet.cfg')
		os.system('sync')
		return

	def set_voip(self):
		os.system('cp /usr/local/lgvp/vdci.cfg /usr/local/lgvp/vdci.cfg.BAK')
		os.system('cp /usr/local/lgvp/vdci.cfg.VQ /usr/local/lgvp/vdci.cfg')
		os.system('sync')
		return

	def recover_network(self):
		os.system('mv /usr/etc/ethernet.cfg.BAK  /usr/etc/ethernet.cfg')
		os.system('sync')
		return
	
	def recover_voip(self):
		os.system('mv /usr/local/lgvp/vdci.cfg.BAK /usr/local/lgvp/vdci.cfg')
		os.system('sync')
		return

	def activate(self, index):
		if self.voice_qulity_test_flag == True:
			self.recover_network()
			self.recover_voip()
			os.system('rm -f /usr/etc/testmodeVQ')
			os.system('killall python')
		else:
			self.set_network()
			self.set_voip()
			os.system('touch /usr/etc/testmodeVQ')
			os.system('killall python')

class BasicCallTestStage(ListStage):
	def __init__(self):
		self.choice = _('Voice quality measure mode'),  _('Registration') # _('IP call test')

		ListStage.__init__(self, self.choice)

	def activate(self,index):
		if index == 0:
			stage = VoiceQualityTestStage()
		elif index == 1:
			stage = TestMenuRegistrationStage()
		elif index == 2:
			stage = DirectCallTeststage
			
		runtime.manager.stack_stage (stage)
		return

		
class DirectCallTeststage(Stage):
	def __init__(self):
		#EntryStage.__init__(self, _('Host address'), _('ADDRESS'))
		self.ui = ui.NormalDigitEditUI('', 'Direct IP call', 'IP address', 30)
		self.ui.set_left('')
		self.ui.set_text('1000@192.168.0.1')

	def handle_key(self, key):
		if key in (config.Green, 'OK', config.Menu1):
			self.AudioCall()
			return True
		elif key == config.Video:
			self.VideoCall()
			return True	
		else:
			#return EntryStage.handle_key(self, key)
			return self.ui.handle_key(key)
			
	def AudioCall(self):
		data = self.ui.get_text()
		if data.find('@') >= 0:
			num, ip= data.split('@')
		else:
			num = data
			ip = None			
		status.dial_number = num
			
		spkOffHook = runtime.SP_context.SPK_OffHook()
		if spkOffHook.next():
			spkOffHook.next()
	
		#runtime.manager.start_ip_call(dest, direct=True)
		runtime.manager.start_ip_call(number=status.dial_number, video_call=False, direct=True, hostName = ip )
		return True

	def VideoCall(self):
		data = self.ui.get_text()
		if data.find('@') >= 0:
			num, ip= data.split('@')
		else:
			num = data
			ip = None			
		status.dial_number = num

		spkOffHook = runtime.SP_context.SPK_OffHook()
		if spkOffHook.next():
			spkOffHook.next()		
		
		# KA: [20080503] added
		from mmiSoundPath import SP_Context
		runtime.SP_context.setBaseCallStatus(SP_Context.OUTGOING_VIDEO)
		#runtime.mmiDebug.mmiTrace('video call start')
		runtime.SP_context.stopTonePlay()
		status.videocall_byuser = True
		runtime.manager.start_ip_call(number=status.dial_number, video_call=True, direct=True, hostName = ip)
		#runtime.manager.start_ip_call(dest, video_call=True, direct=True, tstmode=True)
		# KA: [20080503] added ==

	def destroy(self):
		Stage.destroy(self)



class AdministrationStage(ListStage):
	titleimage = uiconfig.title_admin
	icon = uiconfig.setting_admin_icon
	domonitor_forbidden = True
	def __init__(self):
		self.title = _('ADMINISTRATION')
		#self.choice = _('Information'), _('Network information'), _('VoIP information'), _('VoIP setting'), _('SMS/MMS settings'), _('Manual upgrade'), \
		#		_('KT Mega AP profile setting'), _('Other settings'), _('Base factory initialization'), _('Reboot')

		self.choice = _('Information'), _('Network information'), _('VoIP information'), _('VoIP setting'), _('SMS/MMS settings'), \
					_('Other settings'), _('Base factory initialization'), _('Reboot')
		ListStage.__init__(self, self.choice, self.title)
	def activate(self,index):
		if index == 0:
			stage = InformationStage
		elif index == 1:
			stage = phonesetting.NetworkDetailStage
		elif index == 2:
			stage = phonesetting.VoipDetailStage
		elif index == 3:
			stage = UserInfomation  # voip setting...
		elif index == 4:
			stage = ConfigSMS_MMS_Stage
		elif index == 5:
			stage = ExtraSettingStage
		elif index == 6:
			self.system_reset()
			return
		elif index == 7:
			import time, sys
			import utils, time
			if runtime.vdciapp:
				runtime.vdciapp.req_desubscriber()
				runtime.vdciapp.req_deregister()
			time.sleep(1)	
			utils.releaseDhcp()
#MMW 2008.06.25 when reboot is called, reset vega and DCP related GPIO pin				
			utils.vega_reset_together()
#end of MMW				
#MMW	2008.07.07	when reboot send disassoc to AP and then unload the driver
			os.system('wlstop')
#end of MMW
			time.sleep(1)			
			os.system('reboot')
			sys.exit()
		runtime.manager.stack_stage (stage)
		return
	def handle_key (self, key):
		ret = ListStage.handle_key(self,key)
		if key == config.Menu2:
			from model import MenuStage
			runtime.manager.stack_stage(MenuStage)
			return True
		return ret
	def system_reset(self):
		def yes_cb():
			def reset_cb():
				utils.system_reset()
				
			stage = NotifyStage(_('System reset!'), uiconfig.baloon_setting_system_reset_icon, reset_cb, duration=1)
			runtime.manager.change_stage(stage)
		def no_cb():
			runtime.manager.back_stage()
			
		#stage = YesNoStage(_('Reset system?'), yes_cb, no_cb, '', uiconfig.baloon_setting_system_reset_icon)
		stage = YesNoStage(_('WARNING: All data will delete to factory default. Do you want to proceed?'), yes_cb, no_cb, '', uiconfig.baloon_setting_system_reset_icon)
		
		runtime.manager.stack_stage(stage)


class ManualUpgradeStage(ListStage):
	name = 'manual upgrade'	
	icon = uiconfig.setting_admin_icon
	domonitor_forbidden = True


	def __init__(self):
		self.title = _('Manual Upgrade')
		self.choice =  _('Remote upgrade'), _('Local upgrade')
		ListStage.__init__(self, self.choice)

	def  activate (self, index):
		from profile import profile
		import message
		if index == 0:
			import update
			stage = ConfigManDownStage
			runtime.manager.stack_stage(stage)
		elif index == 1:
			from tstmod import MessageStage
			import tstmod
			ipstr = 'UPDATE from SD/MMC'
			stage = MessageStage('S/W DOWNLOAD',ipstr)
			runtime.manager.stack_stage(stage)
			tstmod.swdown_start(2) # 2== sdmmc


class SoIPProfile(ListStage):
	
	domonitor_forbidden = True

	def __init__(self):
		self.choice = 'SSID', 'BSSID', 'WPA-PSK Key'
		runtime.SoIP_changed = False
		ListStage.__init__(self)
	def activate (self,index):
		if index == 0:
			stage = SoIPSSIDStage
		elif index == 1:
			stage = newprof.SoIPBSSIDMacModeStage
		elif index == 2:
			stage = SoIPWPAPSKStage
		runtime.manager.stack_stage (stage)

	def handle_key(self, key):
		if key in (config.Menu4, config.Red):
			if runtime.SoIP_changed:
				def reset_cb():
					import utils,time
					if runtime.vdciapp:
						runtime.vdciapp.req_deregister()
					time.sleep(1)				
					utils.releaseDhcp()
#MMW 2008.06.25 when reboot is called, reset vega and DCP related GPIO pin				
					utils.vega_reset_together()
#end of MMW	
#MMW	2008.07.07	when reboot send disassoc to AP and then unload the driver
					os.system('wlstop')
#end of MMW
					time.sleep(1)

					os.system('reboot')

				# per KT requirement
				setting.megaAPEnabled = 1
 				setting._save()
				stage = NotifyStage( _('The phone will be reboot shortly'), uiconfig.baloon_setting_system_reset_icon, reset_cb)
				runtime.manager.stack_stage(stage)
				return True
	
		return ListStage.handle_key(self, key)

class SoIPSSIDStage(EntryStage):
	domonitor_forbidden = True
	def __init__(self):
		from profile import wifi_profile_kt_default
		EntryStage.__init__(self, _('ESSID'), _('ESSID'), need_hangul=False)
		self.ui.set_automata('multitap', 'upper')
		self.ui.set_max(32)

		self.old_essid = wifi_profile_kt_default.essid
		if wifi_profile_kt_default.essid:
			self.ui.set_text(wifi_profile_kt_default.essid)


	def activate_menu1(self):
		
		from profile import wifi_profile_kt_default
		old_essid = wifi_profile_kt_default.essid
		str_domain = self.ui.get_text()

		if old_essid != str_domain:
			runtime.SoIP_changed = True
		
		if len(str_domain) > 0:
			wifi_profile_kt_default.set_essid(str_domain)
			wifi_profile_kt_default.save()				
			#runtime.manager.change_stage(NotifyStage(_('SoIP Essid changed'), uiconfig.baloon_wifi_icon))	
			runtime.manager.change_stage(NotifyStage(_('SSID set'), uiconfig.baloon_wifi_icon))				
		else:
			runtime.manager.change_stage(NotifyStage(_('No SSID set.'), uiconfig.baloon_wifi_icon))	
		return True

	def handle_key(self, key):
		if key == config.Red:
			return True
			
		return EntryStage.handle_key(self, key)
		
		

class SoIPWPAPSKStage(Stage):
	domonitor_forbidden = True
#MMW 2007.04.28
	def __init__(self):
		from profile import wifi_profile_kt_default
		
		self.ui = baseui.EntryUI( _('OK'), _('BACK'), _('WPA-PSK(TKIP)'), _('Enter passphrase'), menu4=_('BACK'), need_hangul=False)
		self.ui.set_max(64)
		self.ui.entry.ascii_mode_case0 = True		
		# English only	
		self.ui.set_automata('multitap', 'upper')	
		self.automata_idx = 3

		keyval = wifi_profile_kt_default.wpa_psk_tkip

		if len(keyval) == 66 and keyval[:2] == '0x':
			keyval = keyval[2:]
			
		self.old_key = keyval
		self.ui.set_text(keyval)
#Roxia End smyook

	def show(self):
		#status.password_style = True
		Stage.show(self)

	def hide(self):
		#status.password_style = False
		Stage.hide(self)

	def destroy(self):
		#status.password_style = False
		Stage.destroy(self)

	def activate_menu1(self):
		from profile import wifi_profile_kt_default
		text = self.ui.get_text()
		
		if len(text) == 64:
			for i in text:
				if '0123456789abcdefABCDEF'.find(i) == -1:
					runtime.manager.stack_stage(NotifyStage(_('Invalid input value.')+'\n'+_('When you input 64 char. You must use hexadecimal input value'), uiconfig.baloon_wifi_icon))
					return None
			text = '0x' + text
			wifi_profile_kt_default.wpa_psk_tkip = text
			wifi_profile_kt_default.save()
			
		elif len(text)>=8 and len(text)<=63:
			wifi_profile_kt_default.wpa_psk_tkip = text
			wifi_profile_kt_default.save()
			# 07.08 wifi_profile.save()
			status.profile_detail_changed = True
		else:
			runtime.manager.stack_stage(NotifyStage(_('Input 8~63 characters'), uiconfig.baloon_wifi_icon))

		if wifi_profile_kt_default.wpa_psk_tkip != self.old_key:
			runtime.SoIP_changed = True
						
		def Backstage_cb():
			runtime.manager.back_stage()
		runtime.manager.change_stage(NotifyStage(_('Passphrase set'), uiconfig.baloon_wifi_icon, Backstage_cb))

	def insert_symbol(self, s):
		self.ui.insert_text(s)
		runtime.manager.back_stage()

	def handle_key(self, key):
		if key in '1234567890*' and self.ui.entry.full() and not self.ui.entry._automata._last_ch:
			runtime.manager.stack_stage(NotifyStage(_('Maximum Passphrase Size is 63.'), uiconfig.baloon_wifi_icon))
		elif key == config.Menu1:	#options Menu(left key)
			self.ui.reset_automata()
			self.activate_menu1()
		elif key == config.Menu2:
			if self.ui.handle_key(key):
				return True
			runtime.manager.back_stage()
# shchun : obselete
#		elif key == 'SOFT4':	
#			# vpark 2007.08.28 automata		
#			self.automata_idx = (self.automata_idx + 1) % len(config.automata_list)	
#			self.ui.automata = config.automata_list[self.automata_idx]				
#			self.ui.set_automata(*self.ui.automata)		
#			return True
		elif key == config.Menu4:
			runtime.manager.back_stage()

		elif key == config.Red:
			debugLogN('skip:Red -  SoIPWPAPSKStage')
			return True

		else:
			return self.ui.handle_key(key)
		return True


class InformationStage(Stage):
	domonitor_forbidden = True
	def __init__(self):
		#self.ui = baseui.WhiteUI('', _('BACK'), _('Information'), '')
		self.ui = baseui.LargeWindowUI('', '', '',  _('Information'), '', _('BACK'))

		first_column=90
		second_column=250
		first_row=70
		row_space=19
		details_font = 'HYGothic_V1.00', 11
		details_color = uiconfig.color_dark_gray
		
		t = runtime.evas.text()
		t.font=details_font
		t.color=details_color
		t.text= _('Model Name')
		t.pos =(first_column, first_row)
		self.ui.add(t)
		rstr = open('/usr/local/lgvp/var/product_model.info').read()
		t = runtime.evas.text()
		t.font=details_font
		t.color=details_color
		t.text= rstr.split('#')[1]
		t.pos =(second_column, first_row)
		self.ui.add(t)

		t = runtime.evas.text()
		t.font=details_font
		t.color=details_color
		t.text=_('Manufacturer') # _('Company Name')		
		t.pos =(first_column, first_row + row_space)
		self.ui.add(t)
		rstr = open('/usr/local/lgvp/var/product_model.info').read()
		t = runtime.evas.text()
		t.font=details_font
		t.color=details_color
		t.text= rstr.split('#')[0]
		t.pos =(second_column, first_row + row_space)
		self.ui.add(t)

		t = runtime.evas.text()
		t.font=details_font
		t.color=details_color
		t.text= _('H/W Version')
		t.pos =(first_column, first_row + 2 * row_space)
		self.ui.add(t)
		try:
			p = file("config.cfg",'r')
			t=p.read()
			p.close()
			import re
			t = t.replace(' ','')
			hwver = re.search("hardware_version=([0-9.]+)",t).group(1)
		except:
			hwver = swver = 'not available'
		t = runtime.evas.text()
		t.font=details_font
		t.color=details_color
		t.text='Rel. %s' % hwver
		t.pos =(second_column, first_row + 2 * row_space)
		self.ui.add(t)

		t = runtime.evas.text()
		t.font=details_font
		t.color=details_color
		t.text= _('S/W Version')
		t.pos =(first_column, first_row + 3 * row_space)
		self.ui.add(t)
		rstr = open('/usr/local/lgvp/var/product_model.info').read()
		t = runtime.evas.text()
		t.font=details_font
		t.color=details_color
		t.text='Rel. %s' % rstr.split('#')[2].strip()
		t.pos =(second_column, first_row + 3 * row_space)
		self.ui.add(t)

		t = runtime.evas.text()
		t.font=details_font
		t.color=details_color
		t.text= _('CPU usage.') #_('CPU usage')
		t.pos =(first_column, first_row + 4 * row_space)
		self.ui.add(t)
		t = runtime.evas.text()
		t.font=details_font
		t.color=details_color
		v = get_cpu_usage()
		if v==0:
			v=1
		t.text='%d%%' % v
		t.pos =(second_column, first_row + 4 * row_space)
		self.ui.add(t)

		t = runtime.evas.text()
		t.font=details_font
		t.color=details_color
		t.text= _('Memory usage') # _('Used/Total Memory')
		t.pos =(first_column, first_row + 5 * row_space)
		self.ui.add(t)
		t = runtime.evas.text()
		t.font=details_font
		t.color=details_color
		total, used = get_mem_info()
		t.text='%d/%d KB' % (used,total)
		t.pos =(second_column, first_row + 5 * row_space)
		self.ui.add(t)

		t = runtime.evas.text()
		t.font=details_font
		t.color=details_color
		t.text= _('Flash memory usage.') #_('Flash Memory')
		t.pos =(first_column, first_row + 6 * row_space)
		self.ui.add(t)
		t = runtime.evas.text()
		t.font=details_font
		t.color=details_color
		total, used = get_flash_info()
		t.text='%d/%d KB'%(used,total)
		t.pos =(second_column, first_row + 6 * row_space)
		self.ui.add(t)

	def handle_key(self, key):		
		if key == config.Menu4 or key == 'CLR':
			runtime.manager.back_stage()
			return True
		return False


def get_cpu_usage():
	proc_file = file("/proc/stat", "r")
	
	for line in proc_file:
		if line.startswith("cpu"):
			old=line.split()
			break
	
	proc_file.close()
	
	time.sleep(2)
	
	proc_file = file("/proc/stat", "r")
	
	for line in proc_file:
		if line.startswith("cpu"):
			new=line.split()
			break

	proc_file.close()
	try:	
		usage = (int(new[3]) -int(old[3]))*100 / (int(new[4])-int(old[4]) + int(new[1]) - int(old[1]) + int(new[3])-int(old[3])+int(new[2]) - int(old[2]))			
	except:
		usage = 0

	#print usage
	return usage
	

def get_mem_info():
	mem_total = 0
	mem_free = 0
	mem_cached = 0
	
	proc_file = file("/proc/meminfo","r")
	for line in proc_file:
		if line.startswith("MemTotal: "):
			mem_total = int(line.split()[1])
		elif line.startswith("MemFree: "):
			mem_free = int(line.split()[1])
		elif line.startswith("Cached: "):
			mem_cached = int(line.split()[1])
			
	proc_file.close()

	total_mem_usage = mem_total - int(mem_free + mem_cached*0.75)
	#print mem_total, total_mem_usage
	return mem_total, total_mem_usage


def get_flash_info():
	total_flash = 0
	used_flash = 0
	try:
		fp = os.popen("df", "r")	
		for line in fp:	
			if line.startswith("/dev/stl0/6") or line.startswith("/dev/root"):	
				total_flash = total_flash + int(line.split()[1])
				used_flash = used_flash + int(line.split()[2])
		fp.close()
	except:
		pass
	
	#print total_flash, used_flash
	return total_flash, used_flash

	
class ModelNameStage(Stage):
	def __init__(self):
		import ui
		rstr = open('/usr/local/lgvp/var/product_model.info').read()
		self.ui = ui.ModelNameUI(rstr.split('#')[1])
		self.ui.set_left('')
		self.ui.set_right(_('BACK'))

	def handle_key(self, key):
		if key == config.Menu2:
			runtime.manager.back_stage()
			return True
		return False


class CompanyNameStage(Stage):
	def __init__(self):
		import ui
		rstr = open('/usr/local/lgvp/var/product_model.info').read()
		self.ui = ui.CompanyNameUI(rstr.split('#')[0])
		
		self.ui.set_left('')
		self.ui.set_right(_('BACK'))

	def handle_key(self, key):
		if key == config.Menu2:
			runtime.manager.back_stage()
			return True
		return False


class HWVersionStage(Stage):
	def __init__(self):
		try:
			p = file("config.cfg",'r')
			t=p.read()
			p.close()
			import re
			t = t.replace(' ','')
			hwver = re.search("hardware_version=([0-9.]+)",t).group(1)
		except:
			hwver = swver = 'not available'
		import ui
		self.ui = ui.HWVersionUI( hwver)
		self.ui.set_left('')
		self.ui.set_right(_('BACK'))

	def handle_key(self, key):
		if key == config.Menu2:
			runtime.manager.back_stage()
			return True
		return False


class SWVersionStage(Stage):
	def __init__(self):
		import ui
		rstr = open('/usr/local/lgvp/var/product_model.info').read()
		self.ui = ui.SWVersionUI(rstr.split('#')[2].strip())

		self.ui.set_left('')
		self.ui.set_right(_('BACK'))

	def handle_key(self, key):
		if key == config.Menu2:
			runtime.manager.back_stage()
			return True
		return False


class CpuUsageStage(Stage):
	def __init__(self):
		import ui
		self.ui = ui.CpuUsageUI('%d%%'%get_cpu_usage())
		self.ui.set_left('')
		self.ui.set_right(_('BACK'))

	def handle_key(self, key):
		if key == config.Menu2:
			runtime.manager.back_stage()
			return True
		return False

class TotalMemoryStage(Stage):
	def __init__(self):
		import ui
		total, used = get_mem_info()
		
		self.ui = ui.TotalMemoryUI('%d/%d KB'%(used,total))
		self.ui.set_left('')
		self.ui.set_right(_('BACK'))

	def handle_key(self, key):
		if key == config.Menu2:
			runtime.manager.back_stage()
			return True
		return False


class TotalMemoryUsageStage(Stage):
#obselete
	def __init__(self):
		import ui
		self.ui = ui.TotalMemoryUsageUI('48Mbyte')
		self.ui.set_left('')
		self.ui.set_right(_('BACK'))

	def handle_key(self, key):
		if key == config.Menu2:
			runtime.manager.back_stage()
			return True
		return False


class FlashMemoryStage(Stage):
	def __init__(self):
		import ui

		total, used = get_flash_info()
		self.ui = ui.FlashMemoryUI('%d/%d KB'%(used,total))
		self.ui.set_left('')
		self.ui.set_right(_('BACK'))

	def handle_key(self, key):
		if key == config.Menu2:
			runtime.manager.back_stage()
			return True
		return False


class FlashMemoryUsageStage(Stage):
#obselete
	def __init__(self):
		import ui
		self.ui = ui.FlashMemoryUsageUI('100Mbyte')
		self.ui.set_left('')
		self.ui.set_right(_('BACK'))

	def handle_key(self, key):
		if key == config.Menu2:
			runtime.manager.back_stage()
			return True
		return False

		
###3		
class EtcStage(ListStage):
	titleimage = uiconfig.title_imagesound
	icon = uiconfig.image_sound_icon
	def __init__(self):
		self.title = _('Etc')
		self.choice = _('Session Timer'), _('FIR')

		ListStage.__init__(self, self.choice, self.title)
	def activate(self,index):
		if index == 0:
			stage = SessionTimerStage
		elif index == 1:
			stage = FIRStage
		runtime.manager.stack_stage (stage)

		
class SessionTimerStage(ListStage):
	pass

	
class FIRStage(ListStage):
	titleimage = uiconfig.title_imagesound
	icon = uiconfig.image_sound_icon
	def __init__(self):
		self.title = _('FIR')

		ListStage.__init__(self)
		
	def show(self):
		self.update_addlist()
		ListStage.show(self)
	
	def update_addlist(self):
		self.choice = []
		if setting.subscriber == 1:
			self.choice = [_('Disable')]
		else:
			self.choice = [_('Enable')]
		self.change_choice(self.choice)
	
	def activate(self, index):
		if self.choice[index] == _('Enable'):
			setting.set_subscriber(1)
			message = _('FIR enable')
		elif self.choice[index] == _('Disable'):
			setting.set_subscriber(0)
			message = _('FIR disable')
		stage = FIRNotifyStage(message)
		runtime.manager.change_stage(stage)

class FIRNotifyStage(NotifyStage):
	def __init__(self,message,cb=None):
		icon = uiconfig.baloon_setting_voip_icon
		NotifyStage.__init__(self,message,icon,cb)


class Dect_handset_Stage(ListStage):
	#titleimage = uiconfig.title_dect_list
	
	def __init__(self):
		self.title = _('DECT HANDSET')
		self.name = _('dect handset')

		ListStage.__init__(self)

		self.choice =[]

		self.subscriptionInformationList = self.makeDectInformationList()		
		if len(self.subscriptionInformationList) > 0:
			if self.subscriptionInformationList[0]:
				self.ui.set_left(_('DISCONNECT'))
			else:
				self.ui.set_left('')
		
	def show(self):
		self.subscriptionInformationList = self.makeDectInformationList()

		#self.update_softkey()
		self.update_addlist()
		ListStage.show(self)
		self.update_softkey()

	def update_softkey(self):
		index = self.ui.get_focus()

		if index == -1:
			return

		if self.subscriptionInformationList[index]:
			self.ui.set_left(_('DISCONNECT'))
		else:
			self.ui.set_left('')
		
		ListStage.show(self)

	def update_addlist(self):
		self.choice1=[]

		listLength = len(self.subscriptionInformationList)
		for index in range(listLength):
			if self.subscriptionInformationList[index]:
				inform = _('Handset') + str(index+1) + '  ' + '[' + _('CONNECTED') + ']'
			else:
				inform = _('Handset') + str(index+1) + '  ' + '[' + _('DISCONNECTED') + ']'
			self.choice1.append(inform)

		self.change_choice(self.choice1)

	def makeDectInformationList(self):
		subscriptionInformationList = []
		dectInformationList = runtime.dectCallManager.getDectInformationList()
		for dectInformationItem in dectInformationList:
			subs_info = dectInformationItem.split(':')[0]
			if subs_info == '0':
				subscriptionInformationList.append(False)
			elif subs_info == '1':
				subscriptionInformationList.append(True)
			else:
				runtime.mmiDebug.mmiException('Error Value In subs_info')
				
		return subscriptionInformationList
		
	def activate(self, index):
		index = self.ui.get_focus()

		if self.subscriptionInformationList[index]:
			# send de-sub message
			runtime.dectCallManager.desubscribe(index+1)
			stage = DectDesubscriptionStage()
			runtime.manager.stack_stage(stage)
		
	def handle_key(self,key):
		ret = ListStage.handle_key(self,key)
		if key in ('Up', 'Down'):
			self.update_softkey()
		return ret


class DectDesubscriptionStage(Stage):
	name = "dectDesubscription"
	
	def __init__(self):
		status.supervision_not_allowed = 1

		import ui
		self.ui = ui.dectDesubscribingUI(False)

		import dectConfig
		self.desubscriptionTag = utils.Timer(dectConfig.DESUBSCRIPTION_TIMEOUT, self.desubscriptionFailed)

	def handle_key(self, key):
		if key in (config.Menu2, config.Red, config.CANCEL) :
			return True
			'''
			MD.mmiTrace('DectSubscriptionStage : Menu2 / Red / CANCEL')

			runtime.dectCallManager.cancelSubscription()
			
			self.subscriptionTag = None
			message = _('Subscription cancelled')
			stage = DectSubscriptionNotifyStage(message)
			runtime.manager.change_stage(stage)
			'''

		if key == config.SUCCEED:
			MD.mmiTrace('DectDesubscriptionStage : SUCCEED')

			runtime.dectCallManager.getSnmpInfo()
			
			self.desubscriptionTag = None
			message = _('Desubscription succeeded')
			stage = DectDesubscriptionNotifyStage(message)
			runtime.manager.change_stage(stage)

			return True
			
		elif key == config.FAIL:
			MD.mmiTrace('DectDesubscriptionStage : FAIL')

			self.desubscriptionTag = None
			message = _('Desubscription failed')
			stage = DectDesubscriptionNotifyStage(message)
			runtime.manager.change_stage(stage)

			return True

		return False

	def desubscriptionFailed(self):
		MD.mmiTrace('EVENT :: DectDesubscriptionStage : FAIL')

		self.desubscriptionTag = None
		message = _('Desubscription failed')
		stage = DectDesubscriptionNotifyStage(message)
		runtime.manager.change_stage(stage)
	
	def destroy(self):
		self.desubscriptionTag = None
		Stage.destroy(self)
		status.supervision_not_allowed = 0


class DectDesubscriptionNotifyStage(NotifyStage):
	def __init__(self, message,cb=None):
		icon = uiconfig.baloon_setting_voip_icon
		NotifyStage.__init__(self, message, icon, cb)

####2
class CallTestStage(ListStage):
	titleimage = uiconfig.title_imagesound
	icon = uiconfig.image_sound_icon
	
	def __init__(self):
		self.title = _('CallTestStage')
		self.choice = _('Telephone number'), _('Iteration.'), _('Call duration'), _('Call interval'), _('Start voice call'), _('Start video call')
	
		ListStage.__init__(self,self.choice,self.title)

		self.telephoneNumber = ''
		self.iteration = '100'
		self.callDuration = '20'
		self.interval = '15'

	def activate(self,index):
		if index == 0 :
			stage = BasicEditor(_('Telephone number'), _('Input Telephone number:'), self.telephonenumber_cb, text=self.telephoneNumber, textmax = 20, only_num = 2)
			runtime.manager.stack_stage(stage)
		elif index == 1:
			stage = BasicEditor(_('Iteration'), _('Iteration.'), self.iteration_cb, text=self.iteration, textmax = 4, only_num = 2)
			runtime.manager.stack_stage(stage)
		elif index == 2:
			stage = BasicEditor(_('call duration'), _('Call duration'), self.callDuration_cb, text=self.callDuration, textmax = 4, only_num = 2)
			runtime.manager.stack_stage(stage)
		elif index == 3:
			stage = BasicEditor(_('Interval'), _('Call interval'), self.interval_cb, text=self.interval, textmax = 4, only_num = 2)
			runtime.manager.stack_stage(stage)
		elif index == 4: # audio call
			if self.telephoneNumber:
				status.KT_CALL_TESTER = KtCallTest(self.telephoneNumber, self.iteration, self.callDuration, self.interval, KtCallTest.AUDIO)
				status.KT_CALL_TESTER.startAudioCallTest()
		elif index == 5: # video call
			if self.telephoneNumber:
				status.KT_CALL_TESTER = KtCallTest(self.telephoneNumber, self.iteration, self.callDuration, self.interval, KtCallTest.VIDEO)
				status.KT_CALL_TESTER.startVideoCallTest()

		return

	def telephonenumber_cb(self, ui):
		self.telephoneNumber = ui.get_text()
		if len(self.telephoneNumber) == 0:
			runtime.manager.stack_stage(VoIPSettingNotifyStage(_('No telephone number inserted.')))
		else:
			runtime.manager.change_stage(VoIPSettingNotifyStage(_('Telephone number set')))

	def iteration_cb(self, ui):
		self.iteration = ui.get_text()
		if len(self.iteration) == 0:
			runtime.manager.stack_stage(VoIPSettingNotifyStage(_('No iteration inserted.')))
		else:
			runtime.manager.change_stage(VoIPSettingNotifyStage(_('Iteration set')))

	def callDuration_cb(self, ui):
		self.callDuration = ui.get_text()
		if len(self.callDuration) == 0:
			runtime.manager.stack_stage(VoIPSettingNotifyStage(_('No call duration inserted.')))
		else:
			runtime.manager.change_stage(VoIPSettingNotifyStage(_('Call duration set')))

	def interval_cb(self, ui):
		self.interval = ui.get_text()
		if len(self.interval) == 0:
			runtime.manager.stack_stage(VoIPSettingNotifyStage(_('No interval inserted.')))
		else:
			runtime.manager.change_stage(VoIPSettingNotifyStage(_('Interval set')))


class KtCallTest:
	AUDIO = 1
	VIDEO = 2
	
	def __init__(self, telephoneNumber, iteration, callDuration, interval, callType):
		self.telephoneNumber = telephoneNumber
		self.iteration = int(iteration)
		self.callDuration = int(callDuration)
		self.interval = int(interval) + 1
		self.callType = callType

		self.callTestTimer = None
		
	def getInterval(self):
		return self.interval

	def getCallDuration(self):
		return self.callDuration

	def restartTestCall(self):
		print('**************************************')
		print('CALL TEST : # ', self.iteration)
		print('**************************************')
		
		if self.callType == self.AUDIO:
			self.callTestTimer = utils.Timer(self.interval*1000, self.startAudioCallTest)
			self.iteration = self.iteration - 1
		else:
			self.callTestTimer = utils.Timer(self.interval*1000, self.startVideoCallTest)
			self.iteration = self.iteration - 1

	def startAudioCallTest(self):
		if self.iteration <= 0:
			status.KT_CALL_TESTER = None
			self.callTestTimer = None
			return

		self.callType = self.AUDIO
		
		from mmiSoundPath import SP_Context
		spkOffHook = runtime.SP_context.SPK_OffHook()
		if spkOffHook.next():
			spkOffHook.next()
		
		runtime.SP_context.setBaseCallStatus(SP_Context.OUTGOING_AUDIO)
		runtime.SP_context.setBaseStatus(SP_Context.DIALING)

		runtime.manager.start_call(self.telephoneNumber)

	def startVideoCallTest(self):
		if self.iteration <= 0:
			status.KT_CALL_TESTER = None
			self.callTestTimer = None
			return

		self.callType = self.VIDEO

		from mmiSoundPath import SP_Context
		spkOffHook = runtime.SP_context.SPK_OffHook()
		if spkOffHook.next():
			spkOffHook.next()
		
		runtime.SP_context.setBaseCallStatus(SP_Context.OUTGOING_VIDEO)
		runtime.SP_context.setBaseStatus(SP_Context.DIALING)

		runtime.manager.start_call(self.telephoneNumber, video_call=True)

		
class SmsTestStage(ListStage):
	
	titleimage = uiconfig.title_imagesound
	icon = uiconfig.image_sound_icon
	
	def __init__(self):
		self.title = _('CallTestStage')
		self.choice = _('Telephone number'), _('Iteration'), _('Interval'), _('Audio call test'), _('Video call test')

		ListStage.__init__(self,self.choice,self.title)

	def activate(self,index):
		from phonesetting import NetworkDetailStage, DHCPSettingStage
		if index == 0 :		stage = PPPoE_Stage
		elif index == 1:	stage = DHCPSettingStage
		elif index == 2:	stage = StaticIPStage
		elif index == 3:	stage = NetworkDetailStage
		#if index == 1:	stage = phonesetting.LANSettingStage
		#if index == 2:	stage = UserInfomation
		#if index == 3:	stage = ExtraSettingStage
		runtime.manager.stack_stage(stage)
		return


class NetworkStage(ListStage):
	titleimage = uiconfig.title_imagesound
	icon = uiconfig.image_sound_icon
	def __init__(self):
		self.title = _('NETWORK')
		#choice = _('PPPoE'),_('Network Setting'), ('VoIP'), _('Extra Setting')
		self.choice = _('PPPoE'),_('DHCP'), _('Static IP'),_('Status')

		ListStage.__init__(self,self.choice,self.title)
	def activate(self,index):
		from phonesetting import NetworkDetailStage, DHCPSettingStage
		if index == 0 :		stage = PPPoE_Stage
		elif index == 1:	stage = DHCPSettingStage
		elif index == 2:	stage = StaticIPStage
		elif index == 3:	stage = NetworkDetailStage
		#if index == 1:	stage = phonesetting.LANSettingStage
		#if index == 2:	stage = UserInfomation
		#if index == 3:	stage = ExtraSettingStage
		runtime.manager.stack_stage(stage)
		return


class StaticIPStage(ListStage):
	def __init__(self):
		self.choice = _('IP addrress'), _('Subnet Mask'), _('Gateway'), _('DNS1'), _('DNS2')
		ListStage.__init__(self)
		
	def activate (self, index):
		from phonesetting import IPAddressStage, SubnetmaskStage, GatewayStage, DNSStage,  DNS2Stage
		if index == 0:		stage = IPAddressStage
		if index == 1:		stage = SubnetmaskStage
		if index == 2:		stage = GatewayStage
		if index == 3:		stage = DNSStage
		if index == 4:		stage = DNS2Stage
		runtime.manager.stack_stage(stage)


class ExtraSettingStage(ListStage):
	#titleimage = uiconfig.title_imagesound
	icon = uiconfig.setting_voip_icon
	domonitor_forbidden = True

	def __init__(self):
		self.title = _('EXTRA SETTING')
	
		#self.choice =( _('SMS setting'), _('QoS Marking'),_('DTMF Transmission'),_('URISetting'),_('PREMIUM IP'), _('Manual Download'),\
		#	_('Local Upgrade'),_('Factory Reset'),_('Reboot'), _('MMS setting'))
		self.choice =( _('QoS Marking.'), _('DTMF Sending'), _('URI Setting'), _('Premium IP allocation'), _('Audio/Video setting') )
		ListStage.__init__(self, choice=self.choice, title=self.title)

	def  activate (self, index):
		#from profile import profile
		#import message
		if index == 0:
			#stage = QoSMarkingStage
			stage = NewQoSMarkingStage
		elif index == 1:
			#stage = DTMFSetStage
			stage = NewDTMFSetStage
		elif index == 2:
			#stage = URISettingStage
			stage = NewURISettingStage
		elif index == 3:
			#stage = PremiumIPStage
			stage = NewPremiumIPStage
		elif index == 4:
			stage = CodecPriority
		runtime.manager.stack_stage(stage)
	

class NewQoSMarkingStage(Stage):
	name = 'QoSMarkingstage'
	domonitor_forbidden = True	
	def __init__(self):
		self.ui = baseui.AdminExtraSettingQoSUI(_('SAVE'), '',  '', _('BACK'))
	
	def handle_key(self,key):
		if key == config.Menu1 or key == 'OK':
			setting.subscriber = self.ui.camera_brightness.get_index()			
			if runtime.vdciapp:
				if setting.subscriber == 1:
					runtime.vdciapp.send_mesg(code1=config.MESG_SET_PARAMS, \
						code2=config.MESG_GET_QoS_Marking, \
						mesg1=2, mesg2=160)
					setting.set_subscriber(1)
					#message = _('QoS enable')
					message = _('QoS seting enabled')
				else: 
					runtime.vdciapp.send_mesg(code1=config.MESG_SET_PARAMS, \
						code2=config.MESG_GET_QoS_Marking, \
						mesg1=2, mesg2=0)
					setting.set_subscriber(0)
					#message = _('QoS disable')
					message = _('QoS setting disabled')
			else:
				message = _('QoS Setting failed')				
			stage = QoSNotifyStage(message)
			runtime.manager.change_stage(stage)
			return True
		elif key == config.Menu4 or key == 'CLR':
			runtime.manager.back_stage()
			return True
		elif key == 'Right' or key == 'Left':
			self.ui.camera_brightness.handle_key(key)
			return True			
		else:
			return False


class NewDTMFSetStage(Stage):
	name = 'DTMFSet'
	domonitor_forbidden = True	
	def __init__(self):
		self.ui = baseui.AdminExtraSettingDTMFUI(_('SAVE'), '',  '', _('BACK'))
	
	def handle_key(self,key):
		if key == config.Menu1 or key == 'OK':
			if self.ui.camera_brightness.get_index() == 0:
				#message = _('DTMF In-Band enable')
				message = _('Inband set')
				setting.set_dtmf('0')
			else:
				#message = _('DMTF Out-Band enable')
				message = _('Out of band set')
				setting.set_dtmf('1')
			stage = VoIPSettingNotifyStage(message)
			runtime.manager.change_stage(stage)			
			return True
		elif key == config.Menu4 or key == 'CLR':
			runtime.manager.back_stage()
			return True
		elif key == 'Right' or key == 'Left':
			self.ui.camera_brightness.handle_key(key)
			return True			
		else:
			return False


class NewURISettingStage(Stage):
	name = 'URISettingstage'
	domonitor_forbidden = True	
	def __init__(self):
		self.ui = baseui.AdminExtraSettingURIUI(_('SAVE'), '',  '', _('BACK'))
	
	def handle_key(self,key):
		if key == config.Menu1 or key == 'OK':
			if self.ui.camera_brightness.get_index()==0:
				message = _('KT URI set')
				setting.set_urlPolicy(1)
			else :
				message = _('Standard URI set')
				setting.set_urlPolicy(2)
			stage = NotifyStage(message, uiconfig.image_sound_icon)
			runtime.manager.change_stage(stage)			
			return True
		elif key == config.Menu4 or key == 'CLR':
			runtime.manager.back_stage()
			return True
		elif key == 'Right' or key == 'Left':
			self.ui.camera_brightness.handle_key(key)
			return True			
		else:
			return False


class NewPremiumIPStage(Stage):
	name = 'PremiumIPstage'
	domonitor_forbidden = True	
	def __init__(self):
		self.ui = baseui.AdminExtraSettingPremiumIPUI(_('SAVE'), '',  '', _('BACK'))
	
	def handle_key(self,key):
		if key == config.Menu1 or key == 'OK':
			from vdcisetting import vdci_setting
			if self.ui.camera_brightness.get_index() == 0:
				vdci_setting.premium_ip = 1
				vdci_setting.save()
				#message = _('Premium IP enable')
				message = 'Premuim IP set'# out of translation : KT only.
			else:
				vdci_setting.premium_ip = 0
				vdci_setting.save()
				#message = _('Premium IP disable')
				message = 'Kornet IP set'# out of translation : KT only.

			from profile import profile, lan_profile, wifi_profile
			if profile.get_profile() == 1: #_ethernet
				if lan_profile.get_dhcp() == 1:
					os.system('stop_dhcpclient eth0')
					time.sleep(5)
					os.system('start_dhclient eth0')
			elif profile.get_profile() == 2:
				if wifi_profile.get_dhcp() == 1:
					os.system('stop_dhcpclient wlan0')
					time.sleep(5)
					os.system('start_dhclient wlan0')

			#def cb_function():
			#	runtime.manager.change_stage(ConfirmManualRebootYesNo)				
			#stage = QoSNotifyStage(message, cb_function)
			stage = QoSNotifyStage(message)
			runtime.manager.change_stage(stage)			
		elif key == config.Menu4 or key == 'CLR':
			runtime.manager.back_stage()
			return True
		elif key == 'Right' or key == 'Left':
			self.ui.camera_brightness.handle_key(key)
			return True			
		else:
			return False


class ConfigManDownStage(ListStage):
	name = 'manual download'	
	icon = uiconfig.setting_admin_icon
	domonitor_forbidden = True
	
	def __init__(self):
		self.title = _('Manual Download')

		self.choice =  _('Settings.'), _('Start upgrade')
		ListStage.__init__(self, self.choice)

	def activate(self, index):
		import update
		if index == 1:
			stage = update.ConfirmManualDownloadYesNo
			runtime.manager.stack_stage(stage)

		elif index == 0:
			stage = update.ConfigManualDownload
			runtime.manager.stack_stage(stage)
			

class ConfigSMS_MMS_Stage(ListStage):
	name = 'sms mms config'	
	domonitor_forbidden = True
	icon = uiconfig.setting_admin_icon

	def __init__(self):
		self.title = _('SMS/MMS OPTIONS')
		self.choice =  'SMS', 'MMS'
		ListStage.__init__(self, self.choice)

	def activate(self, index):
		import update
		if index == 0:
			stage = ConfigSMSServer
			runtime.manager.stack_stage(stage)

		elif index == 1:
			stage = ConfigMMSServer
			runtime.manager.stack_stage(stage)

class ConfigSMSServer(ListStage):
	name = 'sms config'	
	icon = uiconfig.setting_admin_icon
	domonitor_forbidden = True
	def __init__(self):
		self.title = _('SMS OPTIONS')
		self.choice =  _('SMS user'), _('SMS host')
		ListStage.__init__(self, self.choice)

	def set_user(self, ui):
		text = ui.get_text()
		if len(text) == 0:
			runtime.manager.stack_stage(VoIPSettingNotifyStage(_('No text inserted.')))
		else:
			setting.set_sms_user(text.strip())
			runtime.manager.change_stage(VoIPSettingNotifyStage(_('SMS user set')))
	def set_host(self, ui):
		text = ui.get_text()
		if len(text) == 0:
			runtime.manager.stack_stage(VoIPSettingNotifyStage(_('No text inserted.')))
		else:
			setting.set_sms_host(text.strip())
			runtime.manager.change_stage(VoIPSettingNotifyStage(_('SMS host set')))
			
	def activate(self, index):		
		if index == 0:
			#stage = ConfigSMSServerIp
			value = setting.sms_user 
			title = _('SMS user name')
			subtitle = _('SMS user name')
			max = 50
			stage = VoIPEditor(title, subtitle, self.set_user, text=value, textmax = max, ischr=True)
			runtime.manager.stack_stage(stage)

		elif index == 1:
			#stage = ConfigSMSServerIp
			value = setting.sms_host
			title =  _('SMS host name')
			subtitle =  _('SMS host name')
			max = 50
			stage = VoIPEditor(title, subtitle, self.set_host, text=value, textmax = max, ischr=True)			
			runtime.manager.stack_stage(stage)


class ConfigMMSServer(ListStage):
	name = 'mms config'	
	icon = uiconfig.setting_admin_icon
	domonitor_forbidden = True
	def __init__(self):
		self.title = _('MMS OPTIONS')
		self.choice =  _('MMS user'), _('MMS host') #, _('MMS http server')
		ListStage.__init__(self, self.choice)

	def set_user(self, ui):
		text = ui.get_text()
		if len(text) == 0:
			runtime.manager.stack_stage(VoIPSettingNotifyStage(_('No text inserted.')))
		else:
			setting.set_mms_user(text.strip())
			runtime.manager.change_stage(VoIPSettingNotifyStage(_('MMS user set')))
			
	def set_host(self, ui):
		text = ui.get_text()
		if len(text) == 0:
			runtime.manager.stack_stage(VoIPSettingNotifyStage(_('No text inserted.')))
		else:
			setting.set_mms_host(text.strip())
			runtime.manager.change_stage(VoIPSettingNotifyStage(_('MMS host set')))

	def set_server(self, ui):
		text = ui.get_text()
		if len(text) == 0:
			runtime.manager.stack_stage(VoIPSettingNotifyStage(_('No text inserted.')))
		else:
			setting.set_mms_server(text.strip())
			runtime.manager.change_stage(VoIPSettingNotifyStage(_('MMS http server set')))
			
	def activate(self, index):		
		if index == 0:
			#stage = ConfigSMSServerIp
			value = setting.mms_user
			title = _('MMS user name')
			subtitle = _('MMS user name')
			max = 50
			stage = VoIPEditor(title, subtitle, self.set_user, text=value, textmax = max, ischr=True)
			runtime.manager.stack_stage(stage)
		elif index == 1:
			#stage = ConfigSMSServerIp
			value = setting.mms_host
			title = _('MMS host name')
			subtitle = _('MMS host name')
			max = 50
			stage = VoIPEditor(title, subtitle, self.set_host, text=value, textmax = max, ischr=True)		
			runtime.manager.stack_stage(stage)
		elif index == 2:
			value = setting.mms_http_server
			title = _('MMS http server')
			subtitle = _('Proxy address') # for input mode
			max = 50
			stage = VoIPEditor(title, subtitle, self.set_server, text=value, textmax = max, ischr=True)		
			runtime.manager.stack_stage(stage)
		

class ConfigSMSServerPort(Stage):
	icon = uiconfig.setting_admin_icon
	def __init__(self):
		
		from vdcisetting import vdci_setting
		import ui
		self.ui = ui.NormalDigitEditUI('', _('SERVER PORT'), _('port'), 5)
		#if setting.download_server_port:
		#	self.ui.set_text(str(setting.download_server_port))

		
		server_port = vdci_setting.sms_port 
		self.ui.set_text(server_port)

		self.icon = uiconfig.baloon_phone_setting_icon
			
	def handle_key(self, key):
		import basemodel
		from vdcisetting import vdci_setting
		
		if key == config.Menu1:
			str_port = self.ui.get_text()

			vdci_setting.sms_port = str_port
			vdci_setting.save()
			
			if len(str_port) > 0:
				message = _('SMS server port set')
			else:
				message = _('SMS server port deleted')
				
			stage = NotifyStage(message, self.icon)
			runtime.manager.change_stage(stage)			
		else:
			return self.ui.handle_key(key)


class URISettingStage(ListStage):
	titleimage = uiconfig.title_imagesound
	icon = uiconfig.image_sound_icon
	def __init__(self):
		self.title = _('URI') + _('SETTING')
		self.choice = _('KT URI'), _('Standard URI')

		ListStage.__init__(self,self.choice,self.title)
	def activate(self,index):
		if index==0:
			setting.set_urlPolicy(1)
		else :
			setting.set_urlPolicy(2)
		'''
		if index==0:
			stage = SchemeStage
		else :
			stage = SettingURIStage
		'''
		stage = NotifyStage(_('URI set'), uiconfig.image_sound_icon)
		runtime.manager.change_stage(stage)

	
class SchemeStage(ListStage):
	notify_message = _('SIP set'),_('Local set'),_('Global set'),_('Tel set')
	#titleimage = uiconfig.title_imagesound
	icon = uiconfig.image_sound_icon
	def __init__(self):
		self.title = _('SCHEME')
		choice = _('SIP'),_('Local'),_('Global'),_('Tel')
		ListStage.__init__(self, choice)
		if setting.scheme_mode < 3:
			focus = setting.scheme_mode
		else:
			focus = 3
		self.ui.set_focus(focus)
	def activate(self , index):
		if index in (0,1,2,3):
			stage = NotifyStage(self.notify_message[index],uiconfig.image_sound_icon)
			setting.set_scheme_mode(index)
			runtime.manager.change_stage(stage)	

			
class SettingURIStage(ListStage):

	titleimage = uiconfig.title_imagesound
	icon = uiconfig.image_sound_icon
	def __init__(self):
		self.title = _('SETTING')
		self.choice = _('Global'), _('Local')
		ListStage.__init__(self,self.choice,self.title)
	def activate(self,index):
		if index == 0:
			stage = GlobalStage
		else:
			stage = LocalStage
		runtime.manager.stack_stage(stage)

		
class GlobalStage(ListStage):
	titleimage = uiconfig.title_imagesound
	icon = uiconfig.image_sound_icon
	def __init__(self):
		self.title = _('GLOBAL')
		self.choice = _('National code'), _('Local code')

		ListStage.__init__(self,self.choice,self.title)

	def activate(self,index):
		if index == 0:
			code = vdci_setting.auth_pwd
			stage = VoIPEditor(_('NATIONAL CODE'), _('Input National Code'),self.code_cb, text = '' , ischr=True, textmax=6)
			#stage = NationalCodeStage
		else:
			stage = LocalCodeStage
		runtime.manager.stack_stage(stage)
	
	def code_cb(self,ui):
		text = ui.get_text()
		if len(text) == 0:
			runtime.manager.change_stage(NationalCodeNotifyStage(_('National Code deleted')))
		else:
			runtime.manager.change_stage(NationalCodeNotifyStage(_('National Code set')))

	
class LocalStage(ListStage):
	title = _('LOCAL')
	titleimage = uiconfig.title_imagesound
	icon = uiconfig.image_sound_icon
	def __init__(self):
		self.choice = _('Phone Context')
		ListStage.__init__(self,self.choice,self.title)

	def activate(self, index):
		if choice[index] == _('Phone Context'):
			stage = PhoneContextStage
			runtime.manager.stack_stage(stage)

			
class PhoneContextStage(Stage):
	pass

	
class NationalCodeStage(Stage):
	def __init__(self, title, subtitle, cb , text=None, ischr=False, textmax=-1,flag=False):
		self.p_subtitle = subtitle
		self.cb = cb
		self.ischr = ischr
		self.flag = flag
		self.ui = baseui.EntryUI( _('OK'), _('BACK'), title,  subtitle)
		self.ui.entry.ascii_mode_case0 = True
		self.ui.set_automata('123', False)
		if textmax != -1:
			self.ui.set_max(textmax)
		if text:
			self.ui.set_text(text)
	
	def t9_add_word(self, word):
		self.ui.entry.t9_add_word(word)
		self.ui.update_entry_info()
	def show(self):
		Stage.show(self)
	def hide(self):
		Stage.hide(self)
	def destroy(self):
		Stage.destroy(self)
	def activate_menu1(self):
		self.cb(self.ui)
	def insert_symbol(self, s):
		before_text = self.ui.get_text()
		self.ui.insert_text(s)
		after_text = self.ui.get_text()
		if before_text == after_text:
			runtime.manager.change_stage(NotifyStage(_('Max length exceeded'), uiconfig.baloon_message_icon))
		else:
			runtime.manager.back_stage()
	def handle_hey(self,key):
		if key == config.Menu1:	#options Menu(left key)
			if self.ui.is_t9_add_word_mode():
				runtime.manager.stack_stage(T9AddWordStage(self))
				return True

			self.ui.reset_automata()
			self.activate_menu1()
		if key == config.Menu2:
			if self.ui.handle_key(key):
				if  len(self.ui.get_text()) == 0:
					self.ui.def_left = ''
					self.ui.set_left('')
				return True
		
		else:
			result = self.ui.handle_key(key)
			if key in '0123456789' and self.ui.get_text():
				self.ui.def_left = _('OK')
				self.ui.set_left(_('OK'))
			return result
		return Trues


class NationalCodeNotifyStage(NotifyStage):
	def __init__(self, message,cb=None):
		icon = uiconfig.baloon_setting_phone_icon
		NotifyStage.__init__(self, message, icon, cb)

		
class LocalCodeStage(ListStage):
	titleimage = uiconfig.title_imagesound
	icon = uiconfig.image_sound_icon
	def __init__(self):
		self.title = _('LOCAL CODE')
		choice = []
		i = 0
		f = open('localcode.txt','r')
		city_name = f.readline()
		self.local_name =city_name.split(',')[:-1]
		city_code = f.readline()
		local_code = city_code.split(',')[:-1]
		f.close()
		for i in range(len(self.local_name)):
			display = self.local_name[i] + '  ' + local_code[i]
			choice.append(display)
			
		ListStage.__init__(self,choice=choice)
		if setting.scheme_mode < len(self.local_name)-1:
			focus = setting.scheme_mode
		else:
			focus = len(self.local_name)-1
		self.ui.set_focus(focus)
	def activate(self , index):
		if index in range(len(self.local_name)):
			stage = NotifyStage(self.local_name[index]+'   '+'set',uiconfig.image_sound_icon)
			setting.set_scheme_mode(index)
			runtime.manager.change_stage(stage)	

			
class AlarmNotifyStage(NotifyStage):
	def __init__(self, message, cb=None):
		NotifyStage.__init__(self, message, uiconfig.baloon_agenda_icon, cb)


class QoSMarkingStage(ListStage): # not used
	name = 'QoSMarkingstage'
	titleimage = uiconfig.title_imagesound
	icon = uiconfig.image_sound_icon
	def __init__(self):
		self.title = _('QoS MARKING')

		ListStage.__init__(self)
		
	def show(self):
		self.update_addlist()
		ListStage.show(self)

	def update_addlist(self):
		self.choice = []
		if setting.subscriber == 1:
			self.choice = [_('Disable')]
		else:
			self.choice = [_('Enable')]
		self.change_choice(self.choice)
	def activate(self, index):
		if self.choice[index] == _('Enable'):
			setting.set_subscriber(1)
			message = _('QoS enable')
		elif self.choice[index] == _('Disable'):
			setting.set_subscriber(0)
			message = _('QoS disable')
		stage = QoSNotifyStage(message)
		runtime.manager.change_stage(stage)


class PremiumIPStage(ListStage):
	name = 'PremiumIPstage'
	#titleimage = uiconfig.title_imagesound
	#icon = uiconfig.image_sound_icon
	def __init__(self):
		self.title = _('Premium IP')
		ListStage.__init__(self)
		
	def show(self):
		self.update_addlist()
		ListStage.show(self)
		from vdcisetting import vdci_setting
		if vdci_setting.premium_ip == 0:
			self.set_focus(1)

	def update_addlist(self):
		self.choice = []
		#from vdcisetting import vdci_setting
		#if vdci_setting.premium_ip == 1:
		#	self.choice = [_('Disable')]
		#else:
		#	self.choice = [_('Enable')]
		self.choice = 'Premium IP',  'Kornet IP' # out of translation : KT only.
		self.change_choice(self.choice)
	def activate(self, index):
		from vdcisetting import vdci_setting
		if index == 0:
			vdci_setting.premium_ip = 1
			vdci_setting.save()
			#message = _('Premium IP enable')
			message = 'Premuim IP set' # out of translation : KT only.
		elif index == 1:
			vdci_setting.premium_ip = 0
			vdci_setting.save()
			#message = _('Premium IP disable')
			message = 'Kornet IP set' # out of translation : KT only.

		from profile import profile, lan_profile, wifi_profile
		if profile.get_profile() == 1: #_ethernet
			if lan_profile.get_dhcp() == 1:
				os.system('stop_dhcpclient eth0')
				time.sleep(5)
				os.system('start_dhclient eth0')
		elif profile.get_profile() == 2:
			if wifi_profile.get_dhcp() == 1:
				os.system('stop_dhcpclient wlan0')
				time.sleep(5)
				os.system('start_dhclient wlan0')

		#def cb_function():
		#	runtime.manager.change_stage(ConfirmManualRebootYesNo)				
		#stage = QoSNotifyStage(message, cb_function)
		stage = QoSNotifyStage(message)
		runtime.manager.change_stage(stage)
			
		
class QoSNotifyStage(NotifyStage):
	def __init__(self, message,cb=None):
		icon = uiconfig.baloon_setting_voip_icon
		NotifyStage.__init__(self, message, icon, cb)

class ConfirmManualRebootYesNo(YesNoStage):
	def __init__(self):
		YesNoStage.__init__(self, _('Reboot the system now?'), self.yes_cb, self.no_cb, '', uiconfig.baloon_setting_voip_icon)

	def yes_cb(self):
#MMW 2008.06.25 when reboot is called, reset vega and DCP related GPIO pin				
		utils.vega_reset_together()
#end of MMW		
#MMW	2008.07.07	when reboot send disassoc to AP and then unload the driver
		os.system('wlstop')
#end of MMW
		os.system('reboot')

	def no_cb(self):
		runtime.manager.back_stage()
		
	def handle_key(self, key):
		if key == config.Red:
			self.no_cb()
			return True
		else:
			return YesNoStage.handle_key(self, key)

class PPPoE_Stage(ListStage):
	titleimage = uiconfig.title_imagesound
	icon = uiconfig.image_sound_icon
	def __init__(self):
		self.title = _('PPPoE')
		self.choice = _('PPPoE ID'),_('PPPoE PW')

		ListStage.__init__(self, self.choice, self.title)
	def activate(self,index):
		if self.choice[index] == _('PPPoE ID'):
			id = vdci_setting.auth_name
			stage = PPPoE_Editor(_('ID'),_('Input ID'),self.ID_cb, text = id, ischr=True, textmax=50)
		elif self.choice[index] ==_('PPPoE PW'):
			password = vdci_setting.auth_pwd
			stage = PPPoE_Editor(_('PASSWORD'),_('Input Password'),self.password_cb, text='', textmax=50)
		#elif self.choice[index] == _('Apply'):
		#	f = open ('/usr/local/ppp/pap-secrets','w')
		#	f.write('%s \t*\t%f\t*',text1,text2)
		#	f.close()
		#	f = open ('/usr/local/ppp/chap-secrets','w')
		#	f.write('%s \t*\t%f\t*',text1,text2)
		#	f.close()
		runtime.manager.stack_stage(stage)
	
	def ID_cb(self,ui):
		text = ui.get_text()
		if len(text) == 0:
			runtime.manager.change_stage(PPoESettingNotifyStage(_('ID deleted')))
		else:
			runtime.manager.change_stage(PPoESettingNotifyStage(_('ID set')))
	def password_cb(self,ui):
		text  = ui.get_text()
		if len(text) == 0:
			runtime.manager.change_stage(PPoESettingNotifyStage(_('Password deleted')))
		else:
			runtime.manager.change_stage(PPoESettingNotifyStage(_('Password set')))
		
class PPoESettingNotifyStage(NotifyStage):
	def __init__(self, message,cb=None):
		icon = uiconfig.baloon_setting_phone_icon
		NotifyStage.__init__(self, message, icon, cb)


class PPPoE_Editor(Stage):
	def __init__(self, title, subtitle, cb, text=None, ischr=False, textmax=-1,flag=False):
		self.p_subtitle = subtitle
		self.cb = cb
		self.ischr = ischr
		self.flag = flag
		self.ui = baseui.EntryUI( _('OK'), _('BACK'), title,  subtitle)
		if subtitle == _('Input ID'):
			self.ui.entry.ascii_mode_case1 = True
			self.ui.set_automata('multitap', 'lower')
		elif subtitle == _('Input Password'):
			self.ui.entry.ascii_mode_case2 = True
			self.ui.set_automata('123', False)
		if textmax != -1:
			self.ui.set_max(textmax)
		if text:
			self.ui.set_text(text)

	def show(self):
		if self.p_subtitle == _('Input Password'):
			status.password_style = True #(mac dinh o status password_style = False)
		Stage.show(self)

	def hide(self):
		if self.p_subtitle == _('Input Password'):
			status.password_style = False
		Stage.hide(self)

	def destroy(self):
		if self.p_subtitle == _('Input Password'):
			status.password_style = False
		Stage.destroy(self)

	def t9_add_word(self, word):
		self.ui.entry.t9_add_word(word)
		self.ui.update_entry_info()

	def activate_menu1(self):
		self.cb(self.ui)

	def insert_symbol(self, s):
		before_text = self.ui.get_text()
		self.ui.insert_text(s)
		after_text = self.ui.get_text()
		if before_text == after_text:
			runtime.manager.change_stage(NotifyStage(_('Max length exceeded'), uiconfig.baloon_message_icon))
		else:
			runtime.manager.back_stage()

	def handle_key(self, key):
		if key == config.Menu1:	#options Menu(left key)
			if self.ui.is_t9_add_word_mode():
				runtime.manager.stack_stage(T9AddWordStage(self))
				return True

			self.ui.reset_automata()
			self.activate_menu1()
		elif key == config.Menu2:
			if self.ui.handle_key(key):
				if  len(self.ui.get_text()) == 0:
					self.ui.def_left = ''
					self.ui.set_left('')
				return True
			runtime.manager.back_stage()
		elif key in '#':
			if self.flag == 0:
				self.ui.set_automata('multitap', 'lower')
				self.flag = 1
			elif self.flag == 1:
				self.ui.set_automata('123', False)
				self.flag = 0
			else:
				self.automata_idx = utils.get_automata_idx(*self.ui.automata)
				self.automata_idx += 1
				if self.automata_idx >= len(config.automata_list):
					self.automata_idx = 3
				name, casemode = config.automata_list[self.automata_idx]
				self.ui.set_automata(name, casemode)
		elif key == '*':	
			if self.ui.entry.ascii_mode_case1:
				runtime.manager.stack_stage(SymbolSelectionStage(self, case=1))
			elif self.ui.entry.ascii_mode_case2:
				runtime.manager.stack_stage(SymbolSelectionStage(self, case=2))
			return True
		else:
			result = self.ui.handle_key(key)
			if key in '0123456789' and self.ui.get_text():
				self.ui.def_left = _('OK')
				self.ui.set_left(_('OK'))
			return result
		return True
		
class SettingResetStage(ListStage):
	name= 'setting reset stage'  # shchun : add name 
	#titleimage = uiconfig.title_setting
	icon = uiconfig.phone_setting_icon
	index = 0
	def __init__(self):
		self.title = _('SETTINGS')
		self.choice = (_('Settings reset'), _('Factory default'))
		ListStage.__init__(self, choice=self.choice, title=self.title)
		
	def activate(self, index):
		if index == 0:

			# utils.system_reset()
			confirm_message = _('WARNING: All setting will be deleted to factory default. Do you want to proceed?')
			message = _('Settings reinitialized.')
			def yes_cb():
				def reset_cb():
					setting.reset(reboot = True)
				reset_duration = 3000
				utils.player.play_effect(config.SETTING_SUCCEEDED)
				stage = NotifyStage(message, uiconfig.baloon_setting_system_reset_icon, reset_cb, duration=reset_duration)
				runtime.manager.change_stage(stage)
			def no_cb():
				runtime.manager.queue_backward(2)
			stage = YesNoStage(confirm_message, yes_cb, no_cb, '', uiconfig.baloon_setting_system_reset_icon)
			runtime.manager.stack_stage(stage)
		else:
			def yes_cb():
				def reset_cb():
					utils.system_reset()
					
				stage = NotifyStage(_('Reinitialized to factory default.'), uiconfig.baloon_setting_system_reset_icon, reset_cb, duration=1)
				runtime.manager.change_stage(stage)
			def no_cb():
				runtime.manager.back_stage()
					
			stage = YesNoStage(_('WARNING: All setting including data will be deleted to factory default. Do you want to proceed?'), yes_cb, no_cb, '', uiconfig.baloon_setting_system_reset_icon)
			
			runtime.manager.stack_stage(stage)

			
class CheckPasswordStage(PINInputStage):
	name = 'CheckPassword'
	domonitor_forbidden = True	
	def __init__(self, mode=1):
		self.mode = mode
		PINInputStage.__init__(self, '', '', '', '')

	def activate(self, pin):
		if self.mode == 1:
			if setting.adminPassword == pin:
				stage = AdministrationStage
				runtime.manager.change_stage(stage)
			elif pin == '':
				self.ui.pin= ''
				self.ui.update()
				stage = PasswordNotifyStage(_('Attention'), _('Password'), _('input'), self.mode)
				runtime.manager.stack_stage(stage)	
			else:
				self.ui.pin= ''
				self.ui.update()
				stage = PasswordNotifyStage(_('Warning'), _('Password is'), _('wrong'), self.mode)
				runtime.manager.stack_stage(stage)
			return
				
		elif self.mode == 2:
			if setting.testPassword == pin:			
				stage = KtTestStage
				runtime.manager.change_stage(stage)
			elif pin == '':
				self.ui.pin= ''
				self.ui.update()
				stage = PasswordNotifyStage(_('Attention'), _('Password'), _('input'), self.mode)
				runtime.manager.stack_stage(stage)	
			else:
				self.ui.pin= ''
				self.ui.update()
				stage = PasswordNotifyStage(_('Warning'), _('Password is'), _('wrong'), self.mode)
				runtime.manager.stack_stage(stage)
			return


		if setting.pin == pin:
			
			if self.mode == 3:
				stage = DectSettingStage
				runtime.manager.change_stage(stage)
			elif self.mode == 4:
				#stage = newprof.PrevProfileListStage
				stage = newprof.ProfileListStage
				runtime.manager.change_stage(stage)
			elif self.mode == 5:
				stage = SettingResetStage
				runtime.manager.change_stage(stage)

			elif self.mode == 6:
				stage = DeletePhoneBookStage
				runtime.manager.change_stage(stage)
			# hcryoo:TBR
			elif self.mode == 7:
				from phonesetting import DectResetStage
				stage = phonesetting.DectResetStage
				runtime.manager.change_stage(stage)
			else:
				self.ui.pin= ''
				self.ui.update()
				stage = PasswordNotifyStage(_('Warning'), _('Password is'), _('wrong'))
				runtime.manager.stack_stage(stage)
		elif pin == '':
			self.ui.pin= ''
			self.ui.update()
			stage = PasswordNotifyStage(_('Attention'), _('Password'), _('input'), self.mode)
			runtime.manager.stack_stage(stage)	
		else:
			self.ui.pin= ''
			self.ui.update()
			stage = PasswordNotifyStage(_('Warning'), _('Password is'), _('wrong'), self.mode)
			runtime.manager.stack_stage(stage)
			
	def handle_key(self,key):
		check_mode = False
		if key == config.Menu1 or key == 'OK':
			self.activate(self.ui.pin)
		elif key == config.Menu2 or key == 'CLR':
			if len(self.ui.pin) > 0:
				self.ui.delete_backward()
			elif key == 'CLR':
				runtime.manager.back_stage()
				check_mode = True
		elif key == config.Menu4:
			if self.mode == 1:
				runtime.manager.change_stage(model.IdleStage,True)
			else:
				runtime.manager.back_stage()
				check_mode = True
		else:
			self.ui.handle_key(key)

		if check_mode == True:
			if config.KT_500:
				if self.mode == 4:
					#runtime.manager.stage.set_focus(2) # this is just for icon updating (do you know ddaembbang?)
					runtime.manager.stage.set_focus(3) # 네트워크 설정
				elif self.mode == 5:
					#runtime.manager.stage.set_focus(2) # this is just for icon updating (do you know ddaembbang?)
					#runtime.manager.stage.set_focus(3) # this is just for icon updating (do you know ddaembbang?)
					runtime.manager.stage.set_focus(4) # 전화기 초기화
			else:
				if self.mode == 3:
					runtime.manager.stage.set_focus(1) # 휴대장치 관리
				elif self.mode == 4:
					#runtime.manager.stage.set_focus(3) # this is just for icon updating (do you know ddaembbang?)
					runtime.manager.stage.set_focus(4) # 네트워크 설정
				elif self.mode == 5:
					#runtime.manager.stage.set_focus(3) # this is just for icon updating (do you know ddaembbang?)
					#runtime.manager.stage.set_focus(4) # this is just for icon updating (do you know ddaembbang?)
					runtime.manager.stage.set_focus(5) # 전화기 초기화


			
#Hau[200804] menu -->setting -->password setting
class PasswordSettingStage(PINInputStage):
	name = 'password setting stage'
	def __init__(self):
		PINInputStage.__init__(self, '', '', '', '')
		
	def activate(self, pin):
		if setting.pin == pin:
			stage = ChangePasswordStage
			runtime.manager.stack_stage(stage)
		elif pin == '':
			self.ui.pin= ''
			self.ui.update()
			stage = PasswordNotifyStage(_('Attention'), _('Password'), _('input'))
			runtime.manager.stack_stage(stage)
		elif pin == self.password_reset_password:
			confirm_message = _('Do you want initialize password')
			message = _('Password initialized')
			def yes_cb():
				def reset_cb():
					runtime.manager.back_stage('setting stage')
				setting.change_password('0000')
				setting.save()
				utils.player.play_effect(config.SETTING_SUCCEEDED)
				stage = NotifyStage(message, uiconfig.baloon_setting_system_reset_icon, reset_cb)
				runtime.manager.change_stage(stage)
			def no_cb():
				runtime.manager.back_stage('setting stage')
			stage = YesNoStage(confirm_message, yes_cb, no_cb, '', uiconfig.baloon_setting_system_reset_icon)
			runtime.manager.change_stage(stage)
		else:
			self.ui.pin= ''
			self.ui.update()
			stage = PasswordNotifyStage(_('Warning'), _('Password is'), _('wrong'))
			runtime.manager.stack_stage(stage)	


class ChangePasswordStage(Stage): 
	def __init__(self, left=_('OK'), right='', menu3='', menu4=_('BACK'), unselbarpos=[]):
		self.ui = baseui.ChangePasswordUI(left, right, menu3, menu4, digit_max_len=4)
		self.ui.set_fixed_automata(self.ui.list.entrys[0], '123', False)	
		self.ui.set_fixed_automata(self.ui.list.entrys[1], '123', False)
		self.digits1 = ''
		self.digits2 = ''
		self.pin1 = ''
		self.pin2 = ''
		
	def show(self):
		self.ui.show()
		for ent in self.ui.list.entrys:
			ent.lostFocus()	
		if self.ui.list.focus == 0:
			self.ui.list.entrys[0].showFocus()
		else:
			self.ui.list.entrys[1].showFocus()
	
	def set_right(self,right):	
		self.right = right
		runtime.rb.set_text(self.right)
		
	def set_left(self,left):
		self.left = left
		runtime.lb.set_text(self.left)
		
	def update_underline(self):
		if self.ui.list.focus == 0:
			#print 'focus 0 pai k?',self.ui.list.focus
			self.digits1 = self.ui.list.entrys[0].set_text(self.digits1)
			#print '##########self.digits1',self.digits1
			self.ui.list.entrys[1].lostFocus
			if len(self.pin1) == 0:
				self.set_right('')
			else:
				self.set_right(_('CLEAR'))
		else:
			#print 'focus 1 pai k?',self.ui.list.focus
			self.digits2 = self.ui.list.entrys[1].set_text(self.digits2)
			#print '##########self.digits2',self.digits2
			self.ui.list.entrys[0].lostFocus
			if len(self.pin2) == 0:
				self.set_right('')
			else:
				self.set_right(_('CLEAR'))
			'''
			if len(self.pin2) < len(self.pin1):
				self.set_left('')
			else:
				self.set_left(_('OK'))
			'''
				
	def update(self):
		if self.ui.list.focus == 0:
			self.digits1 = '*' * len(self.pin1)
		else:
			self.digits2 = '*' * len(self.pin2)
		'''
		print '#########update1',self.digits1
		print '#########update2',self.digits2
		print '########self.pin1',self.pin1
		print '########self.pin2',self.pin2
		print '$$$$$$$$len(self.pin1)',len(self.pin1)
		print '$$$$$$$$len(self.pin2)',len(self.pin2)
		'''
		self.update_underline()
		
	def reset(self):
		self.pin1 = ''
		self.pin2 = ''
		self.set_right('')
		self.update()	
		
	def delete_backward(self):
		if self.ui.list.focus == 0:
			if len(self.pin1) >= 1:
				self.pin1 = self.pin1[:-1]
				if len(self.pin1) == 0:
					self.set_right('')
				else:
					self.set_right(_('CLEAR'))
				self.update()	
		if self.ui.list.focus == 1:
			if len(self.pin2) >= 1:
				self.pin2 = self.pin2[:-1]
				if len(self.pin2) == 0:
					self.set_right('')
				else:
					self.set_right(_('CLEAR'))
				self.update()	
	
	def handle_key(self,key):
		new_pw = self.ui.list.entrys[0].get_text()
		confirm_pw = self.ui.list.entrys[1].get_text()
		
		if key == config.Menu1 or key == 'OK':
			if self.ui.list.entrys[0].get_text() == '' or self.ui.list.entrys[1].get_text() == '':
				utils.player.play_effect(config.SETTING_FAILED)
				stage = PasswordNotifyStage(_('Attention'), _('Password'), _('input'), mode=100)
				runtime.manager.stack_stage(stage)
				return True
			if self.pin1 == self.pin2:
				utils.player.play_effect(config.SETTING_SUCCEEDED)
				stage = PasswordNotifyStage(_('Confirm'), _('Password is'), _('changed'), mode=101)
				runtime.manager.change_stage(stage)
				self.password2 = self.pin2+','
				self.password1 = self.pin1+','
				setting.change_password(self.pin2)
				setting.save()
				# ka...2009.01.15 DECT로 PWD변경
				runtime.dectCallManager.sendToDectPWD(self.pin2)				
				return True
			else:
				self.pin2= ''
				self.update()
				self.ui.list.focus = 1
				utils.player.play_effect(config.SETTING_FAILED)
				stage = PasswordNotifyStage(_('Warning'), ('New password is'), _('wrong'))
				runtime.manager.stack_stage(stage)
				return True
		elif key == config.Menu2 or key == 'CLR':
			if self.ui.list.focus == 0:
				if len(self.pin1) > 0:	self.delete_backward()
				elif key == 'CLR':		runtime.manager.back_stage()
			elif self.ui.list.focus == 1:
				if len(self.pin2) > 0:	self.delete_backward()
				elif key == 'CLR':		runtime.manager.back_stage()
			return True
		elif key == config.Menu4:
			runtime.manager.back_stage()
			return True
		elif key in ('Up', 'Down'):
			ret = self.ui.handle_key(key)			
			for ent in self.ui.list.entrys:
				ent.lostFocus()				
			self.ui.list.entrys[self.ui.list.focus].showFocus()
			if self.ui.list.focus == 0:
				if len(self.pin1) == 0:
					self.set_right('')
				else:
					self.set_right(_('CLEAR'))
			else:
				if len(self.pin2) == 0:
					self.set_right('')
				else:
					self.set_right(_('CLEAR'))
			return True
		elif key.isdigit():
			#print 'press key:',key
			self.set_right(_('CLEAR'))
			if self.ui.list.focus == 0:
				self.ui.list.entrys[0].set_text(key)
				if len(self.pin1) < 4:
					self.pin1 += key
					#print 'pin nhap vao',self.pin1
			elif self.ui.list.focus == 1:
				self.ui.list.entrys[1].set_text(key)
				if len(self.pin2) < 4:
					self.pin2 += key
					#print 'pin nhap vao',self.pin2
			self.update()
			return True
		elif key in ('*','#'):
			return True
		else:
			ret = self.ui.list.entrys[self.ui.list.focus].handle_key(key)
			return ret
		return False
		
#Hau[200804] menu -->setting -->password setting

	
class PasswordNotifyStage(Stage):
	def __init__(self, title, message1, message2='', mode=1):
		self.ui = ui.PopupNotifyUI(title, '', '', '', '', message1, message2)
		self.mode = mode
		
	def show(self):
		Stage.show(self)
		runtime.evas.render_now()
		time.sleep(2)
		if self.mode == 6:	# from phonebook
			runtime.manager.back_stage('phonebook')
		elif self.mode == 4: # from net set
			runtime.manager.back_stage('setting stage')
		elif self.mode == 100: # do not change stage
			runtime.manager.back_stage()
		elif self.mode == 101: # go back to setting stage
			runtime.manager.back_stage('setting stage')
		else:
			if runtime.manager.find_stage('password setting stage'):
				runtime.manager.back_stage('password setting stage')
			elif runtime.manager.find_stage('setting stage'):
				runtime.manager.back_stage('setting stage')
			else:
				runtime.manager.queue_backward(2)

	def destroy(self):
		Stage.destroy(self)


#Hau[200804] menu -->setting -->phone information-->update software
class YesNoUpdateStage(Stage):
	name = 'yesnoupdatestage'
	def __init__(self, index=1):
		self.ui = ui.PasswordNotifyUI3(_('OK'), '', '', '' ,_('Confirm'))
		
		self.no_button_image = utils.put_image(uiconfig.button_image, (160, 153))
		self.no_button_image.hide()
		self.ui.add(self.no_button_image)		
		
		self.yes_button_image = utils.put_image(uiconfig.button_image_r, (250, 153))
		self.yes_button_image.hide()
		self.ui.add(self.yes_button_image)		

		#self.stage_bg_image.layer = title_image_layer 
		
		pos3 = 286 - int(len(_('Yes'))/2) - 10, 160
		yes_text = runtime.evas.text(text='Yes', pos=pos3, color=uiconfig.swver_details_color, \
						font=uiconfig.swver_details_font)
		self.ui.add(yes_text)
		
		pos4 = 196 - int(len(_('No'))/2) - 5, 160
		no_text = runtime.evas.text(text='No', pos=pos4, color=uiconfig.swver_details_color, \
						font=uiconfig.swver_details_font)
		self.ui.add(no_text)
		
		self.index = index
		
	def show(self):
		Stage.show(self)
		runtime.evas.render_now()
		
	def destroy(self):
		Stage.destroy(self)

	def hide(self):
		Stage.hide(self)
	
	def update_select(self,index):
		if index == 1:
			self.no_button_image.file = uiconfig.image_dir + uiconfig.button_image
			self.yes_button_image .file = uiconfig.image_dir + uiconfig.button_image_r
		else:
			self.no_button_image.file = uiconfig.image_dir + uiconfig.button_image_r
			self.yes_button_image .file = uiconfig.image_dir + uiconfig.button_image
	def yes_cb(self):
		stage = UpdateProgress
		runtime.manager.stack_stage(stage)
	def no_cb(self):
		from phonesetting import VersionInfomationStage
		stage = VersionInfomationStage
		runtime.manager.stack_stage(stage)
		
	def handle_key(self, key):
		#ret = ListStage.handle_key(self,key)
		if key == 'Left':
			self.index -= 1
			if self.index < 0:
				self.index = 1
			self.update_select(self.index)
		if key == config.Menu1: 
			if self.index == 1:
				self.yes_cb()
			elif self.index == 0:
				self.no_cb()
		elif key == 'Right':
			self.index += 1
			if self.index > 1:
				self.index = 0	
			self.update_select(self.index)
			if key == config.Menu1: self.no_cb()
			else: return False
		#elif ret:
		#	return ret
		return True


class UpdateProgress(Stage):
	def __init__(self):
		self.ui = ui.UpdateProgressUI('','','','')
		
	def show(self):
		Stage.show(self)
		
	def destroy(self):
		Stage.destroy(self)

	def hide(self):
		Stage.hide(self)


#Hau[200804] menu -->setting -->phone information-->update software
class NetworkRegisterStage(Stage):
	def __init__(self,left='',right = _('CLEAR'), menu4=_('BACK'), unselbarpos=[]):
		self.ui = baseui.NetworkRegisterUI('','','',_('BACK'))
		self.ui.set_fixed_automata(self.ui.list.entrys[1],'123', False)	
		self.ui.set_fixed_automata(self.ui.list.entrys[2],'123', False)
		self.ui.set_fixed_automata(self.ui.list.entrys[3],'123', False)
		self.ui.set_fixed_automata(self.ui.list.entrys[4],'123', False)
		self.ui.set_fixed_automata(self.ui.list.entrys[5],'123', False)
		self.address = '000.000.000.000'
		self.ui.list.entrys[1].set_text(self.address)
		self.ui.list.entrys[2].set_text(self.address)
		self.ui.list.entrys[3].set_text(self.address)
		self.ui.list.entrys[4].set_text(self.address)
		self.ui.list.entrys[5].set_text(self.address)
		
	def show(self):
		self.ui.show()
		for ent in self.ui.list.entrys:
			ent.lostFocus()			
		self.ui.list.entrys[0].showFocus()
		
	def destroy(self):
		Stage.destroy(self)
		
	def handle_key(self,key):
		if key == config.Menu4 or key == config.Red:
			runtime.manager.back_stage
			return True
		elif key in ('Up', 'Down'):
			ret = self.ui.handle_key(key)			
			for ent in self.ui.list.entrys:
				ent.lostFocus()				
			self.ui.list.entrys[self.ui.list.focus].showFocus()	
			return ret
		else:
			ret = self.ui.list.entrys[self.ui.list.focus].handle_key(key)
			return ret
		return False

		
class ScreenStage(ListStage):
	name = 'screen stage'
	
	icon = uiconfig.image_sound_icon
	def __init__(self):
		self.title = _('DISPLAY')
		self.choice = _('Background setting'), _('Slideshow setting'),  _('Lighting setting'), _('Camera setting'), _('Substitute setting'), _('Dial number size')

		ListStage.__init__(self)
	def activate(self, index):
		if index == 0:
			stage = BackgroundSettingStage
#		elif index == 1:
#			if (status.get_regstatus_mmi() == 0) and (config.myann_test_flag == False):
#				msg = _('Please use after register to server')
#				stage = NotifyStage(msg, icon = uiconfig.video_call_connect_icon)
#				runtime.manager.stack_stage(stage)
#				return
#				
#			cur_profile=profile.profile.get_profile()
#			if (cur_profile == 1 and not runtime.peek_lanlink()) or \
#						(cur_profile == 2 and not runtime.peek_wifilink()):	
#				msg = _('Check network connection.')
#				stage = NotifyStage(msg, icon = uiconfig.video_call_connect_icon)
#				runtime.manager.stack_stage(stage)
#				return True
#				
#			if runtime.myannapp:
#				import myannapp
#				if not runtime.myannapp.is_running():
#					runtime.manager.stack_stage(myannapp.MyAnnStage(config.BACKGROUND_DOWNLOAD_URL))
#					from eaHandler import EaHandler
#					runtime.eaHandler.activateApplication_browser(destination=EaHandler.BROWSER)
#			return
		elif index == 1:
			stage = ScreensaverStage(_('SAVE'), '', '', _('BACK'))
		elif index == 2:
			stage = LightingSettingStage
		elif index == 3:
			#stage = CameraSettingStage
			stage = NewCameraSettingStage
		elif index == 4:
			stage = PrivacySettingStage			
		elif index == 5:
			stage = DialNumberSizeStage
		else:
			return
		runtime.manager.stack_stage(stage)


class BackgroundSettingStage(ListStage):
	name = 'background setting'
	#titleimage = uiconfig.title_bg_setting
	icon = uiconfig.bg_setting_icon

	def __init__(self):
		self.title = _('BACKGROUND SETTING')
		#self.choice = _('Select background'), _('Screen text'), _('Widget setting'), _('Menu Theme')
		self.choice = _('Select background'), _('Screen text'), _('Widget setting')

	
		ListStage.__init__(self)	
	def activate (self, index):
		if index == 0:		stage = BackGroundStage
		elif index == 1:	stage = EditBackgroundText
		elif index == 2:	stage = WidgetBackground
		elif index == 3:	stage = MenuBackgroundSettingStage
		else:			return
			
		runtime.manager.stack_stage(stage)
		return


#Thang:Widget setting------------------	
class WidgetBackground(Stage):
	def __init__(self):
		index = setting.idle_style 
		self.ui = baseui.WidgetBackgroundUI(index, _('SAVE'), '', '', _('BACK'))
		
	def destroy(self):
		Stage.destroy(self)
		
	def handle_key(self,key):
		if key == config.Menu1 or key == 'OK':
			def cb():
				runtime.manager.back_stage('background setting')
			self.ui.save()
			utils.player.play_effect(config.SETTING_SUCCEEDED)
			runtime.manager.stack_stage(NotifyStage(_('Set is saved'), uiconfig.baloon_photo_icon, cb=cb))
			return True	
		elif key == config.Menu4 or key == 'CLR':				
			runtime.manager.back_stage()
		else:
			self.ui.handle_key(key)
#Thang:Widget setting------------------


class DialNumberSizeStage(Stage):
	def __init__(self,index=0):
		self.ui = baseui.DialNumberSizeUI(index, _('SAVE'), '', '', _('BACK'))

	def destroy(self):
		Stage.destroy(self)		

	def handle_key(self,key):
		if key == config.Menu1 or key == 'OK':
			self.ui.save()
			'''
			if setting.number_size == 0:
				#stage = PasswordNotifyStage(_('Confirm'),_('Dial number'),_('small size is set'))
				message = ('Dial number')+' '+_('small size is set')
			elif setting.number_size == 1:
				#stage = PasswordNotifyStage(_('Confirm'),_('Dial number'),_('normal size is set'))
				message = ('Dial number')+' '+_('normal size is set')
			elif setting.number_size == 2:
				#stage = PasswordNotifyStage(_('Confirm'),_('Dial number'),_('big size is set'))
				message = ('Dial number')+' '+_('big size is set')
			'''
			message = _('Set is saved')
			stage = NotifyStage(message, uiconfig.baloon_phone_setting_icon) # CHECKME icon
			utils.player.play_effect(config.SETTING_SUCCEEDED)
			runtime.manager.change_stage(stage)
			return True
		elif key == config.Menu4 or key == 'CLR':				
			runtime.manager.back_stage()
		else:
			self.ui.handle_key(key)

		
class MenuBackgroundSettingStage (Stage):
	def __init__(self,index=0):
		self.ui = baseui.ChangeMenuBgrUI(index,_('SAVE'),'','',_('BACK'))

	def destroy(self):
		Stage.destroy(self)		

	def handle_key(self,key):
		if key == config.Menu1 or key =='OK':
			self.ui.save()
			utils.player.play_effect(config.SETTING_SUCCEEDED)
			message = _('Set is saved')
			stage = NotifyStage(message, uiconfig.baloon_phone_setting_icon) # CHECKME icon
			runtime.manager.change_stage(stage)
			return True
		elif key == config.Menu4 or key == 'CLR':				
			runtime.manager.back_stage()
		else:
			self.ui.handle_key(key)

# yylee added for Screensaver Setting
class ScreensaverSettingStage(ListStage):
	name = 'screensaver setting'
	#titleimage = uiconfig.title_screensaver_setting
	icon = uiconfig.screensaver_setting_icon

	def __init__(self):
		self.title = _('PHOTO ALBUM')
		self.choice = _('Slideshow setting'), _('Photo Album photos')

		ListStage.__init__(self)


	def activate (self, index):
		if index == 0:	
			stage = ScreensaverStage(_('SAVE'), '', '', _('BACK'))
		elif index == 1:
			import images
			stage = images.SlideshowSelectStage('taken')
		else:
			return
		runtime.manager.stack_stage(stage)
		
class ScreensaverPreviewStage(Stage):
	def __init__(self):
		self.ui=baseui.BaseUI('', '', '', '', '')
		status.slideshow_preview = True

	def show(self):
		setting.start_slideshow(setting.slideshow_list)

	def handle_key(self,key):
		# print "[yylee debug] ScreensaverPreviewStage", key
		setting.stop_slideshow()
		status.slideshow_preview = False
		runtime.manager.back_stage()
		return		
	
		
# Newair7: [20080418] Display Setting-->Screensaver
class ScreensaverStage(Stage):
	name = 'screensaver'
	def __init__(self, left, right, menu3, menu4, titleimage=None, icon=None):		
		self.ui=baseui.BaseUI(left, _('PHOTOS'), _('SCREEN SAVER SETTING'), menu3, menu4)	
		self.ui.show_bg_depth = True
		self.add_screensaver_ui()

	def add_screensaver_ui(self):
		# bg image
		#bg_image = utils.put_image(uiconfig.depth_bg_image, (0, 0))
		#bg_image.hide()
		#self.ui.add(bg_image)

		# title group set
		#name, pos  = uiconfig.Third_title_screensaver
		#title_image = utils.put_image(name, pos)
		#title_image.hide()
		#self.ui.add(title_image)

		# Screensaver Enable Icon
		name, pos = uiconfig.screensaver_icon1
		icon_1 = utils.put_image(name, pos)
		self.ui.add(icon_1)
		'''
		# Screensaver Method Icon
		name, pos = uiconfig.screensaver_icon2
		icon_2 = utils.put_image(name, pos)
		self.ui.add(icon_2)
		'''
		# Screensaver Timer Icon
		name, pos = uiconfig.screensaver_icon2
		icon_2 = utils.put_image(name, pos)
		self.ui.add(icon_2)
		# Slideshow Interval Icon
		name, pos = uiconfig.screensaver_icon3
		icon_3 = utils.put_image(name, pos)
		self.ui.add(icon_3)

		# Screensaver Enable text
		pos=uiconfig.screensaver_label1_pos
		effect_text1 = runtime.evas.text(text=_('Set'),font=uiconfig.input_font,pos=pos,color=uiconfig.list_text_color)
		self.ui.add(effect_text1)
		'''
		# Screensaver Method text
		pos=uiconfig.screensaver_label2_pos
		effect_text2 = runtime.evas.text(text=_('Mode.'),font=uiconfig.input_font,pos=pos,color=uiconfig.list_text_color)
		self.ui.add(effect_text2)
		'''
		# Screensaver Timer text
		pos=uiconfig.screensaver_label2_pos
		effect_text2 = runtime.evas.text(text=_('Time'),font=uiconfig.input_font,pos=pos,color=uiconfig.list_text_color)
		self.ui.add(effect_text2)		
		# Slideshow Interval text
		pos=uiconfig.screensaver_label3_pos
		effect_text3 = runtime.evas.text(text=_('Interval'),font=uiconfig.input_font,pos=pos,color=uiconfig.list_text_color)
		self.ui.add(effect_text3)	
	
		# Screensaver Enable select box (sel box 1)
		pos = uiconfig.screensaver_box1_pos
		self.sel_box1 = utils.put_image(uiconfig.normal_icon_select, pos)
		self.ui.add(self.sel_box1)	
		'''
		# Screensaver Method select box (sel box 2)
		pos = uiconfig.screensaver_box2_pos
		self.sel_box2 = utils.put_image(uiconfig.normal_icon_select, pos)
		self.ui.add(self.sel_box2)
		'''
		# Screensaver Timer select box (sel box 3)
		pos = uiconfig.screensaver_box2_pos
		self.sel_box2 = utils.put_image(uiconfig.normal_icon_select, pos)
		self.ui.add(self.sel_box2)	
		# Slideshow Interval select box (sel box 4)
		pos = uiconfig.screensaver_box3_pos
		self.sel_box3 = utils.put_image(uiconfig.normal_icon_select, pos)
		self.ui.add(self.sel_box3)
		
		# select box (green)
		pos = uiconfig.screensaver_box1_pos
		self.sel_box_r = utils.put_image(uiconfig.normal_icon_select_r,pos)
		self.ui.add(self.sel_box_r)

		# Name????
		self.button_lists_1 = [_('Disable'), _('Enable')]
		#self.button_lists_2 = [_('LCD off'), _('Photo Album')]
		self.button_lists_2 = [_('1 Min After'), _('5 Min After'), _('10 Min After'), _('15 Min After'), _('30 Min After'), _('1 Hour After')]
		self.button_lists_3 = [_('2 Sec'), _('5 Sec'), _('10 Sec'), _('20 Sec'), _('30 Sec'), _('1 Min')]

		self.button_lists_1_index = setting.screensaver_set_flag
		#self.button_lists_2_index = setting.slideshow_set_flag
		self.button_lists_2_index = setting.screensaver_time
		self.button_lists_3_index = setting.slideshow_interval	

		# Screensaver Enable value check
		if self.button_lists_1_index < 0 and self.button_lists_1_index >= len(self.button_lists_1):
			setting.screensaver_set_flag = 0
			self.button_lists_1_index = 0
		# Screensaver Timer value check
		if self.button_lists_2_index < 0 and self.button_lists_2_index >= len(self.button_lists_2):
			setting.screensaver_set_flag = 0
			self.button_lists_2_index = 0
		'''
		# Slideshow Enable value check
		if self.button_lists_3_index < 0 and self.button_lists_3_index >= len(self.button_lists_3):
			setting.screensaver_set_flag = 0
			self.button_lists_3_index = 0
		'''
		# Slideshow Interval value check
		if self.button_lists_3_index < 0 and self.button_lists_3_index >= len(self.button_lists_4):
			setting.screensaver_set_flag = 0
			self.button_lists_3_index = 0
		
		screensaver_set_flag_text= self.button_lists_1[self.button_lists_1_index ]
		#slideshow_set_flag_text= self.button_lists_2[self.button_lists_2_index ]
		screensaver_time_text = self.button_lists_2[self.button_lists_2_index]
		slideshow_interval_text = self.button_lists_3[self.button_lists_3_index]

		self.screensaver_set_flag_text= runtime.evas.text(text=screensaver_set_flag_text, font=uiconfig.input_font,pos=(0,0),color=uiconfig.list_text_color)
		self.align_center(self.screensaver_set_flag_text, uiconfig.screensaver_text1_pos)
		self.ui.add(self.screensaver_set_flag_text)
		#self.slideshow_set_flag_text= runtime.evas.text(text=slideshow_set_flag_text, font=uiconfig.input_font,pos=(0,0),color=uiconfig.list_text_color)
		#self.align_center(self.slideshow_set_flag_text, uiconfig.screensaver_text2_pos)
		#self.ui.add(self.slideshow_set_flag_text)	
		self.screensaver_time_text = runtime.evas.text(text=screensaver_time_text, font=uiconfig.input_font,pos=(0,0),color=uiconfig.list_text_color)
		self.align_center(self.screensaver_time_text,  uiconfig.screensaver_text2_pos)
		self.ui.add(self.screensaver_time_text)
		self.slideshow_interval_text = runtime.evas.text(text=slideshow_interval_text, font=uiconfig.input_font,pos=(0,0),color=uiconfig.list_text_color)
		self.align_center(self.slideshow_interval_text, uiconfig.screensaver_text3_pos)
		self.ui.add(self.slideshow_interval_text)

		self.index = 0
		self.set_focus(self.index)

	def align_center(self, l, pos):
		x, y = pos
		width,height = l.size
		l.move(x - width/2, y)
		
	def set_focus(self,index):
		if index == 0: 		x,y = uiconfig.screensaver_box1_pos
		elif index ==1:	x,y = uiconfig.screensaver_box2_pos
		elif index ==2:	x,y = uiconfig.screensaver_box3_pos
		#elif index ==3:	x,y = uiconfig.screensaver_box4_pos

		self.sel_box_r.move(x,y)
		self.sel_box_r.show()	
		self.ui.set_menu3(_('PREVIEW'))
		'''
		if self.button_lists_2_index == 1:
			self.ui.set_menu3(_('PREVIEW'))
#			self.ui.set_right(_('PHOTO LIST'))
		else:
#			self.ui.set_right('')
			self.ui.set_menu3('')
		'''

	def change_button_1(self, increase=True):
		num = len(self.button_lists_1)
		if increase:
			self.button_lists_1_index += 1
			if self.button_lists_1_index == num: 
				self.button_lists_1_index = 0
		else:
			self.button_lists_1_index -= 1
			if self.button_lists_1_index < 0: 
				self.button_lists_1_index = num-1
			
		button_text1 = self.button_lists_1[self.button_lists_1_index]		
		if config.mmi_debug: 
			print 'button_lists_1 =', self.button_lists_1
			print 'self.button_lists_1_index = ', self.button_lists_1_index			
			print 'button_text1=', button_text1
		self.screensaver_set_flag_text.text_set(button_text1)
		self.align_center(self.screensaver_set_flag_text, uiconfig.screensaver_text1_pos)
		
	'''
	def change_button_2(self, increase=True):
		num = len(self.button_lists_2)
		if increase:
			self.button_lists_2_index += 1
			if self.button_lists_2_index == num: 
				self.button_lists_2_index = 0
		else:
			self.button_lists_2_index -= 1
			if self.button_lists_2_index < 0: 
				self.button_lists_2_index = num-1
			
		button_text2 = self.button_lists_2[self.button_lists_2_index]		
		self.slideshow_set_flag_text.text_set(button_text2)
		self.align_center(self.slideshow_set_flag_text, uiconfig.screensaver_text2_pos)

		if self.button_lists_2_index == 1:
			self.ui.set_menu3(_('PREVIEW'))
#			self.ui.set_right(_('PHOTO LIST'))
		else:
#			self.ui.set_right('')
			self.ui.set_menu3('')
	'''
			
	def change_button_2(self, increase=True):
		num = len(self.button_lists_2)
		if increase:
			self.button_lists_2_index += 1
			if self.button_lists_2_index == num: 
				self.button_lists_2_index = 0
		else:
			self.button_lists_2_index -= 1
			if self.button_lists_2_index < 0: 
				self.button_lists_2_index = num-1
		
			
		button_text2 = self.button_lists_2[self.button_lists_2_index]		
		self.screensaver_time_text.text_set(button_text2)
		self.align_center(self.screensaver_time_text,  uiconfig.screensaver_text2_pos)
					
	def change_button_3(self, increase=True):
		num = len(self.button_lists_3)
		if increase:
			self.button_lists_3_index += 1
			if self.button_lists_3_index == num: 
				self.button_lists_3_index = 0
		else:
			self.button_lists_3_index -= 1
			if self.button_lists_3_index < 0: 
				self.button_lists_3_index = num-1
			
		button_text3 = self.button_lists_3[self.button_lists_3_index]		
		self.slideshow_interval_text.text_set(button_text3)
		self.align_center(self.slideshow_interval_text, uiconfig.screensaver_text3_pos)

	'''
	def set_focus(self,index):	 # index : 0~3
		#self.bell_image.show()
		#self.groupbell_image.hide()
		if config.mmi_debug: print 'index=', index
		if index == 0:
		elif index == 1:
		elif index == 2:
		elif index == 3:
		self.sel_box.move(x,y)
		self.sel_box.show()	
	'''

	def handle_key(self,key):
		if key == config.Menu1 or key == 'OK':
			'''
			if self.button_lists_2_index:
				if len(setting.slideshow_list) == 0:
					stage = NotifyStage(_('Image not selected'), uiconfig.baloon_video_icon)
					runtime.manager.stack_stage(stage)
					return True
			'''
			if len(setting.slideshow_list) == 0 and self.button_lists_1_index==1:
				stage = NotifyStage(_('Image not selected'), uiconfig.baloon_video_icon)
				runtime.manager.stack_stage(stage)
				return True
			setting.screensaver_set_flag = self.button_lists_1_index
			#setting.slideshow_set_flag = self.button_lists_2_index
			setting.screensaver_time = self.button_lists_2_index
			setting.slideshow_interval = self.button_lists_3_index
			setting.save()
			if setting.screensaver_set_flag == 1:
				setting.enable_screen_saver()
			else:
				setting.disable_screen_saver()

			utils.player.play_effect(config.SETTING_SUCCEEDED)
			message = _('Set is saved') #_('Screensaver set')
			stage = NotifyStage(message, uiconfig.baloon_phonebook_icon) # CHECKME icon
			runtime.manager.change_stage(stage)
			return True
		elif key == config.Menu2:
			import images
			stage = images.SlideshowSelectStage('taken')
			runtime.manager.stack_stage(stage)
			
			return True
		elif key == config.Menu3:
			#if self.button_lists_2_index != 1:
			#	return True
			if len(setting.slideshow_list) > 0:
				stage = ScreensaverPreviewStage
			else:
				stage = NotifyStage(_('Image not selected'), uiconfig.baloon_video_icon)
			runtime.manager.stack_stage(stage)
			return True
		elif key == config.Menu4 or key == 'CLR':				
			runtime.manager.back_stage()
			return True
		elif key == 'Right':
			if self.index == 0:		self.change_button_1(True)
			elif self.index == 1:	self.change_button_2(True)
			elif self.index == 2:	self.change_button_3(True)
			#elif self.index == 3:	self.change_button_4(True)
			return True			
		elif key == 'Left':	
			if self.index == 0:		self.change_button_1(False)
			elif self.index == 1:	self.change_button_2(False)
			elif self.index == 2:	self.change_button_3(False)
			#elif self.index == 3:	self.change_button_4(False)
			return True
		elif key == 'Down':
			self.index += 1
			if self.index >= 3: 
				self.index = 0
			self.set_focus(self.index)			
			return True
		elif key == 'Up':
			self.index -= 1
			if self.index == -1: 
				self.index = 2
			self.set_focus(self.index)			
			return True			
		elif key == config.OffHook or key == config.Green or key == config.Red or key == config.Video:
			return False
		else:
			if config.mmi_debug: print 'CHECKME more!!! key=', key
			return True

class ScreenOffSettingStage(Stage):
	name = 'screenoff'
	def __init__(self, left, right, menu3, menu4, titleimage=None, icon=None):		
		self.ui=baseui.BaseUI(left, right, _('SCREEN OFF SETTING'), menu3, menu4)	
		self.ui.show_bg_depth = True
		self.add_screenoff_ui()

	def add_screenoff_ui(self):
		# bg image
		#bg_image = utils.put_image(uiconfig.depth_bg_image, (0, 0))
		#bg_image.hide()
		#self.ui.add(bg_image)

		# title group set
		#name, pos  = uiconfig.Third_title_screenoff
		#title_image = utils.put_image(name, pos)
		#title_image.hide()
		#self.ui.add(title_image)

		# ScreenOff Enable Icon
		name, pos = uiconfig.screenoff_icon1
		icon_1 = utils.put_image(name, pos)
		self.ui.add(icon_1)
		# ScreenOff Timer Icon
		name, pos = uiconfig.screenoff_icon2
		icon_2 = utils.put_image(name, pos)
		self.ui.add(icon_2)

		# ScreenOff Enable text
		pos=uiconfig.screenoff_label1_pos
		effect_text1 = runtime.evas.text(text=_('Set'),font=uiconfig.input_font,pos=pos,color=uiconfig.list_text_color)
		self.ui.add(effect_text1)
		# ScreenOff Timer text
		pos=uiconfig.screenoff_label2_pos
		effect_text2 = runtime.evas.text(text=_('Time'),font=uiconfig.input_font,pos=pos,color=uiconfig.list_text_color)
		self.ui.add(effect_text2)		
	
		# ScreenOff Enable select box (sel box 1)
		pos = uiconfig.screenoff_box1_pos
		self.sel_box1 = utils.put_image(uiconfig.normal_icon_select, pos)
		self.ui.add(self.sel_box1)	
		# ScreenOff Timer select box (sel box 2)
		pos = uiconfig.screenoff_box2_pos
		self.sel_box2 = utils.put_image(uiconfig.normal_icon_select, pos)
		self.ui.add(self.sel_box2)
	
		# select box (green)
		pos = uiconfig.screenoff_box1_pos
		self.sel_box_r = utils.put_image(uiconfig.normal_icon_select_r,pos)
		self.ui.add(self.sel_box_r)

		# Name
		self.button_lists_1 = [_('Disable'), _('Enable')]
		#self.button_lists_2 = [_('5 Min After'), _('10 Min After'), _('15 Min After'), _('20 Min After'), _('30 Min After'), _('1 Hour After')]
		self.button_lists_2 = [_('1 Min After'), _('5 Min After'), _('10 Min After'), _('15 Min After'), _('30 Min After'), _('1 Hour After')]

		self.button_lists_1_index = setting.screenoff_set_flag
		self.button_lists_2_index = setting.screenoff_time

		# ScreenOff Enable value check
		if self.button_lists_1_index < 0 and self.button_lists_1_index >= len(self.button_lists_1):
			setting.screenoff_set_flag = 0
			self.button_lists_1_index = 0
		# Screensaver Timer value check
		if self.button_lists_2_index < 0 and self.button_lists_2_index >= len(self.button_lists_2):
			setting.screenoff_set_flag = 0
			self.button_lists_2_index = 3		# default 15min. [ 1, 5, 10, 15, ---]
		
		screenoff_set_flag_text= self.button_lists_1[self.button_lists_1_index ]
		screenoff_time_text = self.button_lists_2[self.button_lists_2_index]

		self.screenoff_set_flag_text= runtime.evas.text(text=screenoff_set_flag_text, font=uiconfig.input_font,pos=(0,0),color=uiconfig.list_text_color)
		self.align_center(self.screenoff_set_flag_text, uiconfig.screenoff_text1_pos)
		self.ui.add(self.screenoff_set_flag_text)

		self.screenoff_time_text = runtime.evas.text(text=screenoff_time_text, font=uiconfig.input_font,pos=(0,0),color=uiconfig.list_text_color)
		self.align_center(self.screenoff_time_text,  uiconfig.screenoff_text2_pos)
		self.ui.add(self.screenoff_time_text)

		self.index = 0
		self.set_focus(self.index)

	def align_center(self, l, pos):
		x, y = pos
		width,height = l.size
		l.move(x - width/2, y)
		
	def set_focus(self,index):
		if index == 0:		x,y = uiconfig.screenoff_box1_pos
		elif index ==1:	x,y = uiconfig.screenoff_box2_pos

		self.sel_box_r.move(x,y)
		self.sel_box_r.show()	

	def change_button_1(self, increase=True):
		num = len(self.button_lists_1)
		if increase:
			self.button_lists_1_index += 1
			if self.button_lists_1_index == num: 
				self.button_lists_1_index = 0
		else:
			self.button_lists_1_index -= 1
			if self.button_lists_1_index < 0: 
				self.button_lists_1_index = num-1
			
		button_text1 = self.button_lists_1[self.button_lists_1_index]		
		if config.mmi_debug: 
			print 'button_lists_1 =', self.button_lists_1
			print 'self.button_lists_1_index = ', self.button_lists_1_index			
			print 'button_text1=', button_text1
		self.screenoff_set_flag_text.text_set(button_text1)
		self.align_center(self.screenoff_set_flag_text, uiconfig.screenoff_text1_pos)
		
	def change_button_2(self, increase=True):
		num = len(self.button_lists_2)
		if increase:
			self.button_lists_2_index += 1
			if self.button_lists_2_index == num: 
				self.button_lists_2_index = 0
		else:
			self.button_lists_2_index -= 1
			if self.button_lists_2_index < 0: 
				self.button_lists_2_index = num-1
		
			
		button_text2 = self.button_lists_2[self.button_lists_2_index]		
		self.screenoff_time_text.text_set(button_text2)
		self.align_center(self.screenoff_time_text,  uiconfig.screenoff_text2_pos)
					
	def handle_key(self,key):
		if key == config.Menu1 or key == 'OK':
			setting.screenoff_set_flag = self.button_lists_1_index
			setting.screenoff_time = self.button_lists_2_index
			setting.save()
			if setting.screenoff_set_flag == 1:
				setting.enable_screen_off()
			else:
				setting.disable_screen_off()

			utils.player.play_effect(config.SETTING_SUCCEEDED)
			message = _('Set is saved') #_('Screensaver set')
			stage = NotifyStage(message, uiconfig.baloon_phonebook_icon) # CHECKME icon
			runtime.manager.change_stage(stage)
			return True
		elif key == config.Menu4 or key == 'CLR':				
			runtime.manager.back_stage()
			return True
		elif key == 'Right':
			if self.index == 0:		self.change_button_1(True)
			elif self.index == 1:	self.change_button_2(True)
			return True			
		elif key == 'Left':	
			if self.index == 0:		self.change_button_1(False)
			elif self.index == 1:	self.change_button_2(False)
			return True
		elif key == 'Down' or key == 'Up':
			if self.index == 0:
				self.index = 1
			elif self.index == 1:
				self.index = 0
			self.set_focus(self.index)			
			return True
		elif key == config.OffHook or key == config.Green or key == config.Red or key == config.Video:
			return False
		else:
			if config.mmi_debug: print 'CHECKME more!!! key=', key
			return True

class BackGroundList(ListStage):
	#titleimage =uiconfig.setting_bg_title
	def __init__(self,choose,index):
		self.choose = choose
		self.index = index
		ListStage.__init__(self,self.choose)
		self.ui.set_focus(self.index)
	def activate(self, index):
		status.background_select_index = index
		runtime.manager.back_stage()

		
class PreviewSimple(ListStage):
	def __init__(self,filename):
		ListStage.__init__(self)
		name = filename
		pos = 0,0
		size = 480,242
		self.image = utils.put_image(name,pos,size)
		self.ui.add(self.image)
		self.ui.set_left('')
	def activate(self, index):		
		runtime.manager.back_stage()	


# 대체영상 설정에서 해제는 없음.
# Default 대체영상으로 Enable 되도록 초기화.
# 
class PrivacySettingStage (Stage):		
	name = 'privacy setting'

	def __init__(self):
		self.ui = baseui.PrivacySettingUI(_('SAVE'), '', '', _('BACK'))
		self.choose = (_('Basic Images'), _('Avatas'), _('My Album'), _('Disable'))
		
		name, pos = uiconfig.setting_privacy_icon
		self.ui.set_icon(name, pos)
		self.ui.set_label(_('Privacy'), pos=uiconfig.setting_privacy_label_pos)
		self.ui.set_catalog(self.choose)

		name, pos = uiconfig.setting_privacy_back1
		self.ui.set_imagebg(name, pos)
		
		self.privacy_category = setting.privacy_category
		if self.privacy_category =='':
			self.privacy_category = 3
		status.privacy_select_index = self.privacy_category

		self.image_dir,self.lists = utils.get_image_gallery_list('privacy')
		self.photo_index = 0
		self.filenames = self.get_current_names()
		self.ui.set_files(self.filenames)
		self.filename = self.get_current_file()
		self.ui.set_image(self.filename)
		
		self.focus = 0

		self.ui.catalog.set_index(self.privacy_category)
		
		name = setting.privacy_image_file
		if name == '':
			name = config.def_privacy_image_file
			setting.privacy_image_file = config.def_privacy_image_file

		if not os.access(name, os.R_OK):
			name = config.def_privacy_image_file
			setting.privacy_image_file = config.def_privacy_image_file
			setting.privacy_category = 0
			self.privacy_category = setting.privacy_category
			status.privacy_select_index = self.privacy_category
			full_path = setting.privacy_image_file
			# 리부팅 시 rc.local에서 /usr/local/lgvp/images/private.jpg'를 '/mfs/ram/images/private.jpg로 복사함.
			#command = 'cp \"%s\" \"%s\"' % (full_path, '/usr/local/lgvp/images/private.jpg')
			#os.system(command)
			# 지금 설정한 것이 바로 다음 call 부터 적용 되게...
			#command = 'cp \"%s\" \"%s\"' % (full_path, '/mfs/ram/images/private.jpg')
			#os.system(command)
			import shutil
			shutil.copyfile(full_path, '/usr/local/lgvp/images/private.jpg')
			shutil.copyfile(full_path,'/mfs/ram/images/private.jpg')

			setting.save()
			
		type = ''
		if self.privacy_category == 0:	type = 'privacy'
		elif self.privacy_category == 1:	type = 'avatas'
		elif self.privacy_category == 2:	type = 'taken'
		elif self.privacy_category == 3:	type = 'privacy'
		
		dot = name.rfind('.')
		if dot >= 0:
			name = name[:dot]
			dir = utils.get_image_dir(type)
			name_start = name.find(dir)

			if name_start >= 0:
				name = name[name_start:]
			name = unicode(name, 'euc-kr').encode('utf-8')

			self.ui.files.set_text(name)
			self.photo_index = self.ui.files.index

		self.ui.image.setImage(setting.privacy_image_file)

	def show(self):
		status.privacy_select_index = setting.privacy_category
		
		
		Stage.show(self)
		if self.focus == 0:			
			self.ui.catalog.setText(self.ui.catalog.choose[status.privacy_select_index])
			self.ui.catalog.index = status.privacy_select_index
			
			self.ui.files.lostFocus()
				
			if self.ui.catalog.index == 0:
				self.image_dir,self.lists = utils.get_jpg_image_gallery_list('privacy')
			elif self.ui.catalog.index == 1:
				self.image_dir,self.lists = utils.get_jpg_image_gallery_list('avatas')
			elif self.ui.catalog.index == 2:
				self.image_dir,self.lists = utils.get_jpg_image_gallery_list('taken')
			elif self.ui.catalog.index == 3:
				self.image_dir,self.lists = utils.get_jpg_image_gallery_list('privacy')
			self.privacy_category = self.ui.catalog.index
			self.ui.files.reset()
			self.filenames = self.get_current_names()
			for name in self.filenames:
				self.ui.files.InsertItem(name)

			self.ui.files.index = -1
			filename = setting.privacy_image_file
			filename = filename.replace(self.image_dir, '')
			dot= filename.rfind('.')
			if dot >= 0:
				filename = filename[:dot]
			filename = unicode(filename, 'euc-kr').encode('utf-8')
			self.ui.files.setText(filename)	
			self.ui.catalog.showFocus()

			self.photo_index = self.ui.files.choose.index(filename)
			self.preview_file(setting.privacy_image_file)

			# print "[yylee debug]", self.photo_index
		
	def get_current_file(self):
		return self.image_dir + self.lists[self.photo_index][0]
		
	def get_current_names(self):
		names = []
		for lst in self.lists:
			name = lst[0]
			dot = name.rfind('.')
			if dot >= 0:
				name = name[:dot]
				# yylee: added for korean file name support
				name = unicode(name, 'euc-kr').encode('utf-8')

			names.append(name)
		return names	
		
	def set_privacy(self):
		if config.mm_debug:
			print 'FIXME: Do Photo set privacy: current index = ', self.photo_index
		full_path = self.get_current_file()
		setting.privacy_category = self.privacy_category
		setting.privacy_image_file = full_path

		# 리부팅 시 rc.local에서 /usr/local/lgvp/images/private.jpg'를 '/mfs/ram/images/private.jpg로 복사함.
		#command = 'cp \"%s\" \"%s\"' % (full_path, '/usr/local/lgvp/images/private.jpg')
		#os.system(command)
		# 지금 설정한 것이 바로 다음 call 부터 적용 되게...
		#command = 'cp \"%s\" \"%s\"' % (full_path, '/mfs/ram/images/private.jpg')
		#os.system(command)
		import shutil
		shutil.copyfile(full_path, '/usr/local/lgvp/images/private.jpg')
		shutil.copyfile(full_path,'/mfs/ram/images/private.jpg')

		
		setting.save()

	def preview_small(self):
		self.filename = self.get_current_file()
		self.ui.image.setImage(self.filename)
		self.ui.image.show()

	def preview_file(self, filename):
		self.ui.image.setImage(filename)
		self.ui.image.show()
		
	def preview_hide(self):
		self.ui.image.hide()
		
	def handle_key(self,key):
		if key == config.Menu1 or key == 'OK':
			'''
 			if self.focus == 0:
 				utils.player.play_effect(config.SETTING_FAILED)
 				stage = NotifyStage(_('Please select privacy image'), uiconfig.baloon_video_icon)
				runtime.manager.stack_stage(stage)
				self.focus = 0
				return False
			'''

			if len(self.filenames) == 0:
				utils.player.play_effect(config.SETTING_FAILED)
				stage = NotifyStage(_('No privacy image available'), uiconfig.baloon_video_icon)
				runtime.manager.stack_stage(stage)
				self.focus = 0
				return False

			imageFile = self.get_current_file()
			if not imageFile.lower().endswith('.jpg'):
				utils.player.play_effect(config.SETTING_FAILED)
				stage = NotifyStage(_('Wrong format for privacy image'), uiconfig.baloon_video_icon)
				runtime.manager.stack_stage(stage)
				self.focus = 0
				return False

			tmp_w, tmp_h = utils.get_img_size(imageFile)
			if tmp_w * tmp_h < 640 * 480 + 1:
				def cb():
					 runtime.manager.back_stage('screen stage')
				utils.player.play_effect(config.SETTING_SUCCEEDED)
				#stage = NotifyStage(_('Privacy Image set.'), uiconfig.baloon_photo_icon)
				stage = NotifyStage(_('Set is saved'), uiconfig.baloon_video_icon, cb=cb)
				runtime.manager.stack_stage(stage)
				runtime.evas.render_now()
				self.set_privacy()
			else:
				utils.player.play_effect(config.SETTING_FAILED)
				stage = NotifyStage(_('Size too big.'), uiconfig.baloon_video_icon)
				runtime.manager.stack_stage(stage)
				self.focus = 0
			return True
			
		elif key == config.Menu3:
			return True
			
		elif key == 'Up':
			if self.ui.catalog.index == 3:
				return True
			self.focus -=1
			if self.focus <0: self.focus = 1
			if self.focus == 0:
				self.ui.catalog.showFocus()
				self.ui.files.lostFocus()
			else:
				self.ui.files.showFocus()
				self.ui.catalog.lostFocus()
			return True
			
		elif key == 'Down':
			if self.ui.catalog.index == 3:
				return True
			self.focus +=1
			if self.focus >1: self.focus = 0
			if self.focus == 0:
				self.ui.catalog.showFocus()
				self.ui.files.lostFocus()
			else:
				self.ui.files.showFocus()
				self.ui.catalog.lostFocus()
			return True
			
		elif key in ('Left','Right'):
			if self.focus == 0:
				self.ui.catalog.showFocus()
				self.ui.files.lostFocus()
				self.ui.catalog.handle_key(key)
				self.photo_index = 0
				
				if self.ui.catalog.index == 0:
					self.image_dir,self.lists = utils.get_jpg_image_gallery_list('privacy')
				elif self.ui.catalog.index == 1:
					self.image_dir,self.lists = utils.get_jpg_image_gallery_list('avatas')
				elif self.ui.catalog.index == 2:
					self.image_dir,self.lists = utils.get_jpg_image_gallery_list('taken')
				elif self.ui.catalog.index == 3:
					self.image_dir,self.lists = utils.get_jpg_image_gallery_list('privacy')
					self.photo_index = 1
				self.privacy_category = self.ui.catalog.index
				self.ui.files.reset()
				self.filenames = self.get_current_names()
				num = len(self.filenames)
				if num == 0:
					self.ui.files.reset()
					self.ui.files.setText(_('None'))
					self.ui.catalog.showFocus()
					self.preview_hide()
					return True
				else:
					for name in self.filenames:
						self.ui.files.InsertItem(name)
					self.ui.files.index = self.photo_index
					self.ui.files.setText(self.ui.files.choose[self.ui.files.index])
			elif self.focus == 1:
				self.ui.catalog.lostFocus()
				self.ui.files.showFocus()

				if len(self.filenames) == 0:
					return True
	
				self.ui.files.handle_key(key)
				self.photo_index = self.ui.files.index
			self.preview_small()
			return True
		elif key == config.Menu4 or key == 'CLR':
			runtime.manager.back_stage()
			return True
		return False


class BackGroundStage (Stage):	
	name = 'background'
	def __init__(self):
		#self.ui = baseui.BackGroundUI(_('SAVE'),_('LIST'),_('PREVIEW'),_('BACK'))
		self.ui = baseui.BackGroundUI(_('SAVE'),'',_('PREVIEW'),_('BACK'))
		self.choose = (_('Basic Images'),_('My Album'),_('Receive Images'))

		name, pos = uiconfig.setting_bg_icon
		self.ui.set_icon(name, pos)
		self.ui.set_label(_('Background'), pos=uiconfig.setting_bg_label_pos)
		self.ui.set_catalog(self.choose, pos=uiconfig.setting_bg_box1_pos)
		category = self.get_category_form_image(setting.bg_image_file)
		# print "[yylee debug] category:", category
		if category != None:
			if category == 'vdc':
				status.background_select_index = 0
			elif category == 'taken':
				status.background_select_index = 1
			else:
				status.background_select_index = 2
				
			self.image_dir,self.lists = utils.get_image_gallery_list(category)
			self.photo_index = self.get_photo_index_form_image(setting.bg_image_file)
		else:
			self.image_dir,self.lists = utils.get_image_gallery_list('vdc')
			self.photo_index = 0
		
		self.filenames = self.get_current_names()
		self.ui.set_files(self.filenames, pos=uiconfig.setting_bg_box2_pos)
		self.filename = self.get_current_file()

		# image background
		name, pos = uiconfig.setting_bg_back1
		self.ui.set_imagebg(name, pos)
		# image (for photo)
		self.ui.set_image(self.filename, pos=uiconfig.setting_bg_img1_pos, size=uiconfig.setting_bg_img_size)
		self.focus = 0
		
	def show(self):
		Stage.show(self)
		if config.mmi_debug: 
			print '## self.focus =', self.focus
			print '## status.background_select_index=', status.background_select_index
		if self.focus == 0:	
			self.ui.catalog.setText(self.ui.catalog.choose[status.background_select_index])
			self.ui.catalog.index = status.background_select_index
			self.ui.files.lostFocus()
			
			if self.ui.catalog.index == 0:
				self.image_dir,self.lists = utils.get_image_gallery_list('vdc')
			elif self.ui.catalog.index == 1:
				self.image_dir,self.lists = utils.get_image_gallery_list('taken')
			elif self.ui.catalog.index == 2:
				self.image_dir,self.lists = utils.get_image_gallery_list('received')

			self.ui.files.reset()
			if len(self.lists) > 0:
				self.filenames = self.get_current_names()
				for name in self.filenames:
					self.ui.files.InsertItem(name)
				self.ui.files.index = self.photo_index
				self.ui.files.setText(self.ui.files.choose[self.ui.files.index])
			else:
				self.ui.files.setText(_('None'))
			
			self.ui.catalog.showFocus()
		else:
			if len(self.ui.files.choose) > 0:
				#self.ui.files.setText(self.ui.files.choose[status.background_select_index])
				self.ui.files.setText(self.ui.files.choose[self.photo_index])
				#self.ui.files.index = status.background_select_index
			self.ui.catalog.lostFocus()
			self.ui.files.showFocus()
		
		#self.photo_index = self.ui.files.index
		if len(self.ui.files.choose) > 0:
			self.preview_small()
		else:
			self.ui.image.hide()
		
	def get_current_file(self):
		return self.image_dir + self.lists[self.photo_index][0]
		
	def get_current_names(self):
		names = []
		for lst in self.lists:
			name = lst[0]
			dot = name.rfind('.')
			if dot >= 0:
				name = name[:dot]
				# yylee: added for korean file name support
				name = unicode(name, 'euc-kr').encode('utf-8')

			names.append(name)
		return names	
		
	def set_background(self):
		if config.mm_debug:
			print 'FIXME: Do Photo set background: current index = ', self.photo_index
		full_path = self.get_current_file()
		setting.bg_image_file = full_path
		import baseui
		baseui.change_bg(runtime.evas, full_path)

	def get_category_form_image(self, image):
		slash = image.rfind('/')
		category = None
		if slash >=0:
			dir = image[:slash]
			# print "[yylee debug] get_category_form_image[%s:%s]"%(image, dir)
			if config.image_bg_dir.find(dir) >= 0:
				category = 'vdc'
			elif config.image_taken_dir.find(dir) >= 0:
				category = 'taken'
			elif config.image_received_dir.find(dir) >= 0:
				category = 'received'
		return category

	def get_photo_index_form_image(self, image):
		slash = image.rfind('/')
		index = 0
		if slash >=0:
			name = image[slash+1:]
			#name = unicode(name, 'euc-kr').encode('utf-8')
			for item in self.lists:
				# print "[yylee debug] get_photo_index_form_image[%s:%s]"%(item[0], name)
				if item[0] == name:
					return index
				index+=1
		status.background_select_index = 0
		self.image_dir,self.lists = utils.get_image_gallery_list('vdc')		
		return 0

	def preview_small(self):
		self.filename = self.get_current_file()
		self.ui.image.setImage(self.filename)
		self.ui.image.show()
		
		
	def handle_key(self,key):
		if key == config.Menu1 or key == 'OK':
			if len(self.ui.files.choose) == 0:
				utils.player.play_effect(config.SETTING_FAILED)
				stage = NotifyStage(_('Background not selected'), uiconfig.baloon_photo_icon)
				runtime.manager.stack_stage(stage)
				return True
				
			imageFile = self.get_current_file()
			tmp_w, tmp_h = utils.get_img_size(imageFile)
			if tmp_w * tmp_h < 640 * 480 + 1:
				def cb():
					runtime.manager.back_stage('background setting')
				utils.player.play_effect(config.SETTING_SUCCEEDED)
				stage = NotifyStage(_('Set is saved'), uiconfig.baloon_photo_icon, cb=cb)
				runtime.manager.stack_stage(stage)
				runtime.evas.render_now()
				self.set_background()
			else:
				utils.player.play_effect(config.SETTING_FAILED)
				stage = NotifyStage(_('Size too big.'), uiconfig.baloon_photo_icon)
				runtime.manager.stack_stage(stage)
			return True

#		elif key == config.Menu2:
#			if self.focus == 0:
#				stage = BackGroundList(self.choose,self.ui.catalog.index)
#			else:
#				if len(self.ui.files.choose) == 0:
#					return True
#				stage = BackGroundList(self.filenames,self.ui.files.index)
#			runtime.manager.stack_stage(stage)	
#			return True

		elif key == config.Menu3:
			if len(self.ui.files.choose) == 0:
				return True
			stage = PreviewSimple(self.filename)
			if config.mmi_debug: 
				print '## self.focus=', self.focus
				print '## status.background_select_index=', status.background_select_index
				print '## self.ui.files.index=', self.ui.files.index
			#	status.background_select_index = self.ui.files.index
			runtime.manager.stack_stage(stage)
			return True
			
		elif key == 'Up':
			self.focus -=1
			if self.focus <0: self.focus = 1
			if self.focus == 0:
				self.ui.catalog.showFocus()
				self.ui.files.lostFocus()
			else:
				self.ui.files.showFocus()
				self.ui.catalog.lostFocus()
			return True
			
		elif key == 'Down':
			self.focus +=1
			if self.focus >1: self.focus = 0
			if self.focus == 0:
				self.ui.catalog.showFocus()
				self.ui.files.lostFocus()
			else:
				self.ui.files.showFocus()
				self.ui.catalog.lostFocus()			
			return True
			
		elif key in ('Left','Right'):
			if self.focus == 0:
				self.ui.catalog.showFocus()
				self.ui.files.lostFocus()
				self.ui.catalog.handle_key(key)
				self.photo_index = 0
				if self.ui.catalog.index == 0:
					self.image_dir,self.lists = utils.get_image_gallery_list('vdc')
					status.background_select_index = 0
				elif self.ui.catalog.index == 1:
					self.image_dir,self.lists = utils.get_image_gallery_list('taken')
					status.background_select_index = 1
				elif self.ui.catalog.index == 2:
					self.image_dir,self.lists = utils.get_image_gallery_list('received')
					status.background_select_index = 2
				self.ui.files.reset()
				if len(self.lists) > 0:
					self.filenames = self.get_current_names()
					for name in self.filenames:
						self.ui.files.InsertItem(name)
					self.ui.files.index = self.photo_index
					self.ui.files.setText(self.ui.files.choose[self.ui.files.index])
				else:
					self.ui.files.setText(_('None'))
			elif self.focus == 1:
				self.ui.catalog.lostFocus()
				self.ui.files.showFocus()
				if len(self.ui.files.choose) > 0:
					self.ui.files.handle_key(key)
					self.photo_index = self.ui.files.index
			if len(self.ui.files.choose) > 0:
				self.preview_small()
			else:
				self.ui.image.hide()
			return True
			
		elif key == config.Menu4 or key == 'CLR':
			runtime.manager.back_stage()
			return True
			
		return False

#Jongwook:Screen Text------------------
class EditBackgroundText(Stage):
	def __init__(self,index=0):
		self.ui = baseui.EditBackgroundTextUI(index, _('SAVE'), '', '', _('BACK'))
		#self.ui.set_fixed_automata(None, False)
		# shchun : global automata change
		if setting.lang == 'Korean':
			self.ui.set_automata('hangul', False)
		else:
			self.ui.set_automata('multitap', 'lower')
		# end shchun
	def destroy(self):
		Stage.destroy(self)

	def handle_key(self,key):
		if key == config.Menu1 or key == 'OK':
			self.ui.save()
			utils.player.play_effect(config.SETTING_SUCCEEDED)
			runtime.manager.change_stage(NotifyStage(_('Set is saved'), uiconfig.baloon_photo_icon))
			return True
		elif key == config.Menu4:				
			runtime.manager.back_stage()
		else:
			self.ui.handle_key(key)
#Jongwook:Screen Text------------------

class NewCameraSettingStage(Stage):
	name = 'new camera setting'
	
	def __init__(self):
		self.ui = baseui.NewCameraSettingUI(_('SAVE'), '',  '', _('BACK'))
	
	def handle_key(self,key):
		if key == config.Menu1 or key == 'OK':
			setting.camera_brightness = self.ui.camera_brightness.get_index()
			setting.camera_white_balance = self.ui.camera_wb.get_index()
			runtime.mmedia.still_preview(config.STILL_CAPTURE_MODE_QVGA, 320, 240, 0, 0)
			utils.camera_brightness_set(setting.camera_brightness)
			utils.camera_wb_set(setting.camera_white_balance)
			runtime.mmedia.unload()
			setting.save()
			utils.player.play_effect(config.SETTING_SUCCEEDED)
			#stage = NotifyStage(_('Camera setting saved'), uiconfig.baloon_phonebook_icon) # CHECKME icon
			stage = NotifyStage(_('Set is saved'), uiconfig.baloon_phonebook_icon) # CHECKME icon
			runtime.manager.change_stage(stage)
			return True
		elif key == config.Menu4 or key == 'CLR':
			runtime.manager.back_stage()
			return True
		elif key == 'Right' or key == 'Left':
			if self.ui.index == 0:				
				self.ui.camera_brightness.handle_key(key)
			else:
				self.ui.camera_wb.handle_key(key)
			return True			
		elif key == 'Up':
			if self.ui.index == 0:
				self.ui.index = 1
			else:
				self.ui.index = 0				
			self.ui.set_focus(self.ui.index)			
			return True
		elif key == 'Down':
			if self.ui.index == 0:
				self.ui.index = 1
			else:
				self.ui.index = 0
			self.ui.set_focus(self.ui.index)
			return True	
			
# yylee added for Camera Setting
class CameraSettingStage(ListStage):


	titleimage = uiconfig.title_camera_setting
	icon = uiconfig.camera_setting_icon

	def __init__(self):
		self.title = _('CAMERA SETTING')
		self.choice = _('Camera Brightness'), _('White Balance')

		ListStage.__init__(self)	
	def activate (self, index):
		if index == 0:
			stage = CameraBrightnessSettingStage
		elif index == 1:
			stage = WhiteBalanceSettingStage
		else:
			return
		runtime.manager.stack_stage(stage)

# yylee added for White Balance Setting
class WhiteBalanceSettingStage(ListStage):

	titleimage = uiconfig.title_cam_wb_setting 
	def __init__(self):
		self.title = _('CAMERA SETTING')
		self.choice = _('Auto'), _('Sunny'), _('Cloudy'), _('Tungsten'), _('Fluorescent') # 자동, 맑음, 흐림, 백열등, 형광등

		ListStage.__init__(self)
		self.ui.set_focus(setting.camera_white_balance)
		
	def activate (self, index):
		setting.camera_white_balance = index

		utils.camera_wb_set(setting.camera_white_balance)
		setting.save()
		utils.player.play_effect(config.SETTING_SUCCEEDED)
		runtime.manager.back_stage()
		

# yylee added for Camera Brightness Setting
class CameraBrightnessSettingStage(ListStage):

	titleimage = uiconfig.title_cam_brightness_setting
	
	def __init__(self):
		self.title = _('CAMERA SETTING')
		self.choice = _('Darkest camera'), _('Darker camera'), _('Normal camera'), _('Lighter camera'), _('Lightest camera')

		ListStage.__init__(self)
		self.ui.set_focus(setting.camera_brightness)
	
	def activate (self, index):
		if index == 0:		setting.camera_brightness  = 0
		elif index == 1:	setting.camera_brightness  = 1
		elif index == 2:	setting.camera_brightness  = 2
		elif index == 3:	setting.camera_brightness = 3
		elif index == 4:	setting.camera_brightness  = 4

		utils.camera_brightness_set(setting.camera_brightness)
		setting.save()
		utils.player.play_effect(config.SETTING_SUCCEEDED)
		
		runtime.manager.back_stage()

		
# yylee added for Lighting Setting
class LightingSettingStage(ListStage):
	#titleimage = uiconfig.title_lighting_setting
	icon = uiconfig.lighting_setting_icon

	def __init__(self):
		self.title = _('LIGHTING SETTING')
		self.choice = _('Screen brightness'), _('Night mode setting'), _('Screen off setting')
	
		ListStage.__init__(self)
	
	def activate (self, index):
		if index == 0:		stage = BrightnessSettingStage
		elif index == 1:	stage = NightmodeSettingStage
		elif index == 2:	stage = ScreenOffSettingStage(_('SAVE'), '', '', _('BACK'))
		else:
			return
		runtime.manager.stack_stage(stage)

# yylee added for Brightness Setting
class BrightnessSettingStage(Stage):
	def __init__(self):
	
		import ui
		self.ui = baseui.BrightnessSettingUI(_('SAVE'), ' ', None, ' ',  _('BACK'))

		self.br_start_xpos = 0
		self.br_start_ypos = 0

		self.br_grade_list = []

		self.br_level = setting.brightness

		runtime.manager.set_brightness(setting.brightness-1)
		runtime.manager.in_night_mode = False
		runtime.manager.stop_nightmode_screenoff_timer()
		
		# Brightness
		name,pos = uiconfig.lighting_brightness_icon
		icon_br = utils.put_image(name,pos)
		self.ui.add(icon_br)
		br_text = runtime.evas.text(text=_('Brightness'),font=uiconfig.phoneinfo_font,pos=(117,113),color=uiconfig.list_text_color)
		self.ui.add(br_text)

		name,pos = uiconfig.lighting_brightness_grade_bg
		br_grade_bg = utils.put_image(name,pos)
		self.ui.add(br_grade_bg)

		self.set_br_start_pos(pos[0], pos[1]+3)
		self.fill_br_grade()

	def destroy(self):
		runtime.manager.handle_lighting()
		if runtime.manager.in_night_mode == False:
			runtime.manager.set_brightness(setting.brightness-1)
		Stage.destroy(self)

	# Set Brightness grade bar start position
	def set_br_start_pos(self, xpos, ypos):
		self.br_start_xpos = xpos
		self.br_start_ypos = ypos

	# grade에 해당하는 image를 1개 그린다.
	def draw_grade(self, start_xpos, start_ypos, grade):
		filler = uiconfig.lighting_grade
		pos = (start_xpos+20+29*grade, start_ypos)
		img = utils.put_image(filler, pos)
		self.ui.add(img)
		return img

	# level 만큼의 grade 그림을 그린다.
	def fill_grade(self, start_xpos, start_ypos, level, list):
		if level < 1:
			return False
		if level > 5:
			return True

		filler = uiconfig.lighting_grade
		i = 0
		while i < level:
			filler_img = self.draw_grade(start_xpos, start_ypos, i)
			list.append(filler_img)
			i = i+1
		return True

	# 처음 화면에 진입하면, 설정된 Brightness Level 만큼 grade를 채운다.
	def fill_br_grade(self):
		self.fill_grade(self.br_start_xpos, self.br_start_ypos, self.br_level, self.br_grade_list)

	# Brightness grade 1개 내리기
	def down_br_grade(self):
		if self.br_level > 1:
			self.br_level = self.br_level-1
			del_img = self.br_grade_list.pop()
			del_img.hide()

	# Brightness grade 1개 올리기
	def up_br_grade(self):
		if self.br_level < 5:
			filler_img = self.draw_grade(self.br_start_xpos, self.br_start_ypos, self.br_level)
			self.br_grade_list.append(filler_img)
			self.br_level = self.br_level+1

			
	def handle_key(self, key):
		if key == config.Menu1 or key == 'OK': #OK
			setting.brightness = self.br_level
			setting.save()
			runtime.manager.handle_lighting()
			if runtime.manager.in_night_mode == False:
				runtime.manager.set_brightness(setting.brightness-1)

			utils.player.play_effect(config.SETTING_SUCCEEDED)
			stage = NotifyStage(_('Set is saved'), uiconfig.baloon_phonebook_icon) # CHECKME icon
			
			runtime.manager.change_stage(stage)
			return True
		elif key == config.Menu4 or key == 'CLR': #BACK
			#runtime.manager.handle_lighting()
			#if runtime.manager.in_night_mode == False:
			#	runtime.manager.set_brightness(setting.brightness-1)
			runtime.manager.back_stage()
			return True
		elif key =='Left':
			self.down_br_grade()
			runtime.manager.set_brightness(self.br_level -1)
			return True
		elif key =='Right':
			self.up_br_grade()
			runtime.manager.set_brightness(self.br_level -1)
			return True
		
		return False

class NightmodeSettingStage(Stage):
	def __init__(self):
		import ui
		self.ui = baseui.NightmodeSettingUI(_('SAVE'), ' ', None, ' ',  _('BACK'))
		self.name = 'nightmode setting'

		self.dark_start_xpos = 0
		self.dark_start_ypos = 0
		self.dark_grade_list = []

		self.dark_level = setting.nightmode_darkness

		self.index = 0
		self.nm_choice = _('Disable'),_('Enable')
		self.screenoff_choice = _('Not Used'), _('Used')
		self.cursor_pos = 0

		self.from_pos = uiconfig.lighting_nightmode_text2_pos
		self.to_pos = uiconfig.lighting_nightmode_text3_pos

		self.from_time = (0,0) 	#(hour,min)
		self.to_time = (0,0)	#(hour,min)		

		# Nightmode
		name,pos = uiconfig.lighting_nightmode_icon
		icon_nm = utils.put_image(name,pos)
		self.ui.add(icon_nm)
		nm_text = runtime.evas.text(text=_('Nightmode'),font=uiconfig.input_font,pos=uiconfig.lighting_nightmode_label1_pos,color=uiconfig.list_text_color)
		self.ui.add(nm_text)
		name,pos = uiconfig.lighting_nightmode_select
		nm_sel_bg = utils.put_image(name,pos)
		self.ui.add(nm_sel_bg)

		name,pos = uiconfig.lighting_nightmode_select_r
		self.nm_sel = utils.put_image(name, pos)
		self.ui.add(self.nm_sel)
		self.nm_sel.hide()

		self.nm_setting_value = setting.nightmode_enable
			
		self.nm_setting = runtime.evas.text(text=self.nm_choice[self.nm_setting_value],font=uiconfig.input_font,pos=uiconfig.lighting_nightmode_text1_pos,color=uiconfig.list_text_color)
		self.align_center(self.nm_setting, uiconfig.lighting_nightmode_text1_pos)
		self.ui.add(self.nm_setting)
		
		# Nightmode From
		name,pos = uiconfig.lighting_nightmode_from_icon
		icon_from = utils.put_image(name,pos)
		self.ui.add(icon_from)
		from_text = runtime.evas.text(text=_('FROM'),font=uiconfig.input_font,pos=uiconfig.lighting_nightmode_label2_pos,color=uiconfig.list_text_color)
		self.ui.add(from_text)

		if setting.nightmode_from_hour != None:
			from_hour  = setting.nightmode_from_hour
		else:
			from_hour = 0

		if setting.nightmode_from_min != None:
			from_min = setting.nightmode_from_min
		else:
			from_min = 0

		self.from_time = (from_hour, from_min)
			
		if self.from_time[0] >= 12:			# hour > 12
			self.set_nm_from_ap = 1
			name,pos = uiconfig.nm_from_icon_pm			
		else:
			self.set_nm_from_ap = 0
			name,pos = uiconfig.nm_from_icon_am

		self.nm_from_ap = utils.put_image(name,pos)
		self.ui.add(self.nm_from_ap)

		if self.set_nm_from_ap == 1: 	# PM
			if self.from_time[0] == 12:
				self.editing_from_text = [(self.from_time[0])/10, (self.from_time[0])%10, self.from_time[1]/10, self.from_time[1]%10]
			else:
				self.editing_from_text = [(self.from_time[0]-12)/10, (self.from_time[0]-12)%10, self.from_time[1]/10, self.from_time[1]%10]
		else:						# AM
			if self.from_time[0] == 0:
				self.editing_from_text = [1, 2, self.from_time[1]/10, self.from_time[1]%10]
			else:
				self.editing_from_text = [(self.from_time[0])/10, (self.from_time[0])%10, self.from_time[1]/10, self.from_time[1]%10]
		self.timeset_from_values = runtime.evas.text(text=self.get_from_text(),font=uiconfig.input_font,pos=uiconfig.lighting_nightmode_text2_pos,color=uiconfig.list_text_color)
		self.ui.add(self.timeset_from_values)
		
		# Nightmode To
		name,pos = uiconfig.lighting_nightmode_to_icon
		icon_to = utils.put_image(name,pos)
		self.ui.add(icon_to)
		to_text = runtime.evas.text(text=_('TO'),font=uiconfig.input_font,pos=uiconfig.lighting_nightmode_label3_pos,color=uiconfig.list_text_color)
		self.ui.add(to_text)

		if setting.nightmode_to_hour != None:
			to_hour  = setting.nightmode_to_hour
		else:
			to_hour = 0

		if setting.nightmode_to_min != None:
			to_min = setting.nightmode_to_min
		else:
			to_min = 0
			
		self.to_time = (to_hour, to_min)
			
		if self.to_time[0] >= 12:			
			self.set_nm_to_ap = 1
			name,pos = uiconfig.nm_to_icon_pm			
		else:
			self.set_nm_to_ap = 0
			name,pos = uiconfig.nm_to_icon_am

		self.nm_to_ap = utils.put_image(name,pos)
		self.ui.add(self.nm_to_ap)

		if self.set_nm_to_ap == 1: 	# PM
			if self.to_time[0] == 12:
				self.editing_to_text = [(self.to_time[0])/10, (self.to_time[0])%10, self.to_time[1]/10, self.to_time[1]%10]
			else:
				self.editing_to_text = [(self.to_time[0]-12)/10, (self.to_time[0]-12)%10, self.to_time[1]/10, self.to_time[1]%10]
		else:						# AM
			if self.to_time[0] == 0:
				self.editing_to_text = [1, 2, self.to_time[1]/10, self.to_time[1]%10]
			else:
				self.editing_to_text = [(self.to_time[0])/10, (self.to_time[0])%10, self.to_time[1]/10, self.to_time[1]%10]
			
		self.timeset_to_values = runtime.evas.text(text=self.get_to_text(),font=uiconfig.input_font,pos=uiconfig.lighting_nightmode_text3_pos,color=uiconfig.list_text_color)
		self.ui.add(self.timeset_to_values)

		# Darkness
		name,pos = uiconfig.lighting_nightmode_dark_icon
		icon_dark = utils.put_image(name,pos)
		self.ui.add(icon_dark)
		dark_text = runtime.evas.text(text=_('Darkness'),font=uiconfig.input_font,pos=uiconfig.lighting_nightmode_label4_pos,color=uiconfig.list_text_color)
		self.ui.add(dark_text)
		name,pos = uiconfig.lighting_dark_grade_bg
		dark_grade_bg = utils.put_image(name,pos)
		self.ui.add(dark_grade_bg)

		self.set_dark_start_pos(pos[0], pos[1]+3)
		self.fill_dark_grade()

		# ScreenOff
		name, pos = uiconfig.lighting_nightmode_screenoff_icon
		icon_screenoff = utils.put_image(name, pos)
		self.ui.add(icon_screenoff)
		screenoff_text = runtime.evas.text(text=_('LCD off'),font=uiconfig.input_font,pos=uiconfig.lighting_nightmode_label5_pos,color=uiconfig.list_text_color)
		self.ui.add(screenoff_text)

		name,pos = uiconfig.lighting_nightmode_screenoff_select
		screenoff_sel_bg = utils.put_image(name, pos)
		self.ui.add(screenoff_sel_bg)
		name,pos = uiconfig.lighting_nightmode_screenoff_select_r
		self.screenoff_sel = utils.put_image(name, pos)
		self.ui.add(self.screenoff_sel)
		self.screenoff_sel.hide()

		self.screenoff_setting_value = setting.nightmode_screenoff_enable
		self.screenoff_setting = runtime.evas.text(text=self.screenoff_choice[self.screenoff_setting_value],font=uiconfig.input_font,pos=uiconfig.lighting_nightmode_text1_pos,color=uiconfig.list_text_color)
		self.align_center(self.screenoff_setting, uiconfig.lighting_nightmode_text4_pos)
		self.ui.add(self.screenoff_setting)

		# underline
		self.underline = runtime.evas.text(text='_', font=uiconfig.phoneinfo_font)
		self.underline.color = uiconfig.date_edit_entry_color
		self.ui.add(self.underline)
		self.underline.hide()

		self.update_from_time()
		self.update_to_time()
		self.set_focus(self.index)

	def align_center(self, l, pos):
		x, y = pos
		width,height = l.size
		l.move(x - width/2, y)

	def show(self):
		Stage.show(self)
		self.underline.hide()
		self.screenoff_sel.hide()

	def update_underline(self, pos):
		font_width = uiconfig.date_edit_char_width
		font_height = uiconfig.date_edit_underline_y
		xpos = (0, 1, 2, 3)[self.cursor_pos]
		
		colon_width = 0
		if self.cursor_pos > 1:
			colon_width = font_width/2
			
		x = pos[0] + xpos * font_width + colon_width
		self.underline.pos = x, pos[1] + font_height

	def get_from_text(self):
		text = "%01d%01d:%01d%01d" % tuple(self.editing_from_text)
		return text

	def get_to_text(self):
		text = "%01d%01d:%01d%01d" % tuple(self.editing_to_text)
		return text
		
	def update_from_time(self,):
		hour = self.editing_from_text[0] * 10 + self.editing_from_text[1]
		min = self.editing_from_text[2] * 10 + self.editing_from_text[3]
		self.from_time = (hour, min)
		self.timeset_from_values.text = self.get_from_text()
		
	def update_to_time(self,):
		hour = self.editing_to_text[0] * 10 + self.editing_to_text[1]
		min = self.editing_to_text[2] * 10 + self.editing_to_text[3]
		self.to_time = (hour, min)
		self.timeset_to_values.text = self.get_to_text()
			
	# Set Darkness grade bar start position
	def set_dark_start_pos(self, xpos, ypos):
		self.dark_start_xpos = xpos
		self.dark_start_ypos = ypos

	# grade에 해당하는 image를 1개 그린다.
	def draw_grade(self, start_xpos, start_ypos, grade):
		filler = uiconfig.lighting_grade
		pos = (start_xpos+20+29*grade, start_ypos)
		img = utils.put_image(filler, pos)
		self.ui.add(img)
		return img

	# level 만큼의 grade 그림을 그린다.
	def fill_grade(self, start_xpos, start_ypos, level, list):
		if level < 1:
			return False
		if level > 5:
			return True

		filler = uiconfig.lighting_grade
		i = 0
		while i < level:
			filler_img = self.draw_grade(start_xpos, start_ypos, i)
			list.append(filler_img)
			i = i+1
		return True
	
	# 처음 화면에 진입하면, 설정된 Darkness Level 만큼 grade를 채운다.
	def fill_dark_grade(self):
		self.fill_grade(self.dark_start_xpos, self.dark_start_ypos, self.dark_level, self.dark_grade_list)

	# Darkness grade 1개 내리기
	def down_dark_grade(self):
		if self.dark_level > 1:
			self.dark_level = self.dark_level-1
			del_img = self.dark_grade_list.pop()
			del_img.hide()

	# Darkness grade 1개 올리기
	def up_dark_grade(self):
		if self.dark_level < 5:
			filler_img = self.draw_grade(self.dark_start_xpos, self.dark_start_ypos, self.dark_level)
			self.dark_grade_list.append(filler_img)
			self.dark_level = self.dark_level+1
		
	def set_focus(self,index):
		# nightmode enable/disable
		if index == 0:
			self.nm_sel.show()
			self.screenoff_sel.hide()
			self.underline.hide()
			self.ui.set_right('')	

			if self.nm_setting_value == 0:
				runtime.manager.set_brightness(setting.brightness-1)
				runtime.manager.in_night_mode = False
				runtime.manager.stop_nightmode_screenoff_timer()

		# from time set
		elif index == 1:
			self.cursor_pos = 0
			self.nm_sel.hide()
			self.screenoff_sel.hide()
			self.underline.show()
			self.update_underline(self.from_pos)
			if self.set_nm_from_ap == 1:
				self.ui.set_right(_('AM'))
			else:
				self.ui.set_right(_('PM'))
			
			if self.nm_setting_value == 0:
				runtime.manager.set_brightness(setting.brightness-1)
				runtime.manager.in_night_mode = False
				runtime.manager.stop_nightmode_screenoff_timer()

		# to time set
		elif index == 2:
			self.cursor_pos = 0
			self.nm_sel.hide()
			self.screenoff_sel.hide()
			self.underline.show()
			self.update_underline(self.to_pos)
			if self.set_nm_to_ap == 1:
				self.ui.set_right(_('AM'))
			else:
				self.ui.set_right(_('PM'))
			
			if self.nm_setting_value == 0:
				runtime.manager.set_brightness(setting.brightness-1)
				runtime.manager.in_night_mode = False
				runtime.manager.stop_nightmode_screenoff_timer()
		
		# nightmode darkness
		elif index == 3:
			self.nm_sel.hide()
			self.screenoff_sel.hide()
			self.underline.hide()
			self.ui.set_right('')
			
			#if self.nm_setting_value == 1:
			runtime.manager.set_darkness(self.dark_level -1)
			runtime.manager.in_night_mode = True
			#runtime.manager.stop_nightmode_screenoff_timer() 
			
		# ScreenOff enable/disable
		elif index == 4:
			self.nm_sel.hide()
			self.screenoff_sel.show()
			self.underline.hide()
			
			if self.nm_setting_value == 0:
				runtime.manager.set_brightness(setting.brightness-1)
				runtime.manager.in_night_mode = False
				runtime.manager.stop_nightmode_screenoff_timer()

		else:
			return False
			
		return True

	
	def handle_key(self, key):
		if key == config.Menu1 or key =='OK': #OK
			setting.nightmode_enable = self.nm_setting_value
				
			if self.set_nm_from_ap == 1: 	# PM
				if self.from_time[0] == 12:
					setting.nightmode_from_hour = self.from_time[0]
				else:
					setting.nightmode_from_hour = self.from_time[0] + 12
			else	:						# AM
				if self.from_time[0] == 12:
					setting.nightmode_from_hour = 0
				else:
					setting.nightmode_from_hour = self.from_time[0]
			setting.nightmode_from_min	= self.from_time[1]

			if self.set_nm_to_ap == 1:		# PM
				if self.to_time[0] == 12:
					setting.nightmode_to_hour 	= self.to_time[0]
				else:
					setting.nightmode_to_hour 	= self.to_time[0] + 12
			else:						# AM
				if self.to_time[0] == 12:
					setting.nightmode_to_hour 	= 0
				else:
					setting.nightmode_to_hour 	= self.to_time[0]
			setting.nightmode_to_min 	= self.to_time[1]
			
			setting.nightmode_darkness	= self.dark_level

			setting.nightmode_screenoff_enable = self.screenoff_setting_value
			
			setting.save()
			if setting.nightmode_enable == 1:
				runtime.manager.start_nightmode_timer()
			else:
				runtime.manager.stop_nightmode_timer()
				
			self.name = ''
			runtime.manager.handle_lighting()
			if runtime.manager.in_night_mode == False:
				runtime.manager.set_brightness(setting.brightness-1)

			utils.player.play_effect(config.SETTING_SUCCEEDED)
			
			stage = NotifyStage(_('Set is saved'), uiconfig.baloon_phonebook_icon) # CHECKME icon
			runtime.manager.change_stage(stage)
			#setting._screen_saver_timer = utils.Timer(100, setting.activate_screen_saver)
			return True
		elif key == config.Menu4 or key == 'CLR': #BACK
			self.name = ''
			runtime.manager.handle_lighting()
			if runtime.manager.in_night_mode == False:
				runtime.manager.set_brightness(setting.brightness-1)
			runtime.manager.back_stage()
			return True
		elif key == config.Menu2:
			if self.index == 1:
				if self.set_nm_from_ap == 1:
					self.set_nm_from_ap = 0
					self.nm_from_ap.file = uiconfig.image_dir + uiconfig.alarm_icon_am[0]
					self.ui.set_right(_('PM'))
				else:
					self.set_nm_from_ap = 1
					self.nm_from_ap.file = uiconfig.image_dir + uiconfig.alarm_icon_pm[0]
					self.ui.set_right(_('AM'))
			elif self.index == 2:
				if self.set_nm_to_ap == 1:
					self.set_nm_to_ap = 0
					self.nm_to_ap.file = uiconfig.image_dir + uiconfig.alarm_icon_am[0]
					self.ui.set_right(_('PM'))
				else:
					self.set_nm_to_ap = 1
					self.nm_to_ap.file = uiconfig.image_dir + uiconfig.alarm_icon_pm[0]
					self.ui.set_right(_('AM'))
		elif key =='Left':
			if self.index == 0:
				self.nm_setting_value = 1 - self.nm_setting_value
				self.nm_setting.text_set(self.nm_choice[self.nm_setting_value])
				
			elif self.index == 1:
				self.cursor_pos = self.cursor_pos - 1
				if self.cursor_pos < 0: self.cursor_pos = 3
				self.underline.show()
				self.update_underline(self.from_pos)
				
			elif self.index == 2:
				self.cursor_pos = self.cursor_pos - 1
				if self.cursor_pos < 0: self.cursor_pos = 3
				self.underline.show()
				self.update_underline(self.to_pos)
		
			elif self.index == 3:
				self.down_dark_grade()
				runtime.manager.set_darkness(self.dark_level -1)
				runtime.manager.in_night_mode = True

			elif self.index == 4:
				if self.screenoff_setting_value == 1:
					self.screenoff_setting_value = 0
				else:
					self.screenoff_setting_value = 1
				print 'screenoff_setting_value =', self.screenoff_setting_value
				self.screenoff_setting.text_set(self.screenoff_choice[self.screenoff_setting_value])
				self.align_center(self.screenoff_setting, uiconfig.lighting_nightmode_text4_pos)
				
			return True
		elif key =='Right':
			if self.index == 0:
				self.nm_setting_value = 1 - self.nm_setting_value
				self.nm_setting.text_set(self.nm_choice[self.nm_setting_value])
				
			elif self.index == 1:
				self.cursor_pos = self.cursor_pos + 1
				if self.cursor_pos > 3: self.cursor_pos = 0
				self.underline.show()
				self.update_underline(self.from_pos)
				
			elif self.index == 2:
				self.cursor_pos = self.cursor_pos + 1
				if self.cursor_pos > 3: self.cursor_pos = 0
				self.underline.show()
				self.update_underline(self.to_pos)
		
			elif self.index == 3:
				self.up_dark_grade()
				runtime.manager.set_darkness(self.dark_level -1)
				runtime.manager.in_night_mode = True

			elif self.index == 4:
				if self.screenoff_setting_value == 1:
					self.screenoff_setting_value = 0
				else:
					self.screenoff_setting_value = 1
				self.screenoff_setting.text_set(self.screenoff_choice[self.screenoff_setting_value])
				self.align_center(self.screenoff_setting, uiconfig.lighting_nightmode_text4_pos)
				
			return True
		elif key == 'Up':
			self.index = self.index - 1
			if self.index < 0:	self.index = 4
			self.set_focus(self.index)
			return True
		elif key == 'Down':
			self.index = self.index + 1
			if self.index > 4:	self.index = 0
			self.set_focus(self.index)
			return True
		elif key in "0123456789":
			if self.index == 1:
				if self.cursor_pos == 0:
					#hour 10
					if not key in "01":
						return True
					if key == '1' and self.editing_from_text[1] > 2:
						self.editing_from_text[1] = 2
				elif self.cursor_pos == 1:
					#hour 1
					if self.editing_from_text[0] == 1 and key not in "012": return True
					hour = self.editing_from_text[0] * 10 + ord(key) - ord('0')
					if hour > 23:
						return True
				elif self.cursor_pos == 2:
					#min 10
					if not key in "012345":
						return True
				elif self.cursor_pos == 3:
					pass
					
				self.editing_from_text[self.cursor_pos] = ord(key) - ord('0')

				self.update_from_time()
				
				self.cursor_pos += 1
				if self.cursor_pos > 3:
					self.cursor_pos = 0
				self.update_underline(self.from_pos)
				return True
				
			elif self.index == 2:
				if self.cursor_pos == 0:
					#hour 10
					if not key in "01":
						return True
					if key == '1' and self.editing_to_text[1] > 2:
						self.editing_to_text[1] = 2
				elif self.cursor_pos == 1:
					#hour 1
					if self.editing_to_text[0] == 1 and key not in "012": return True
					hour = self.editing_to_text[0] * 10 + ord(key) - ord('0')
					if hour > 23:
						return True
				elif self.cursor_pos == 2:
					#min 10
					if not key in "012345":
						return True
				elif self.cursor_pos == 3:
					pass
					
				self.editing_to_text[self.cursor_pos] = ord(key) - ord('0')
				
				self.update_to_time()
				
				self.cursor_pos += 1
				if self.cursor_pos > 3:
					self.cursor_pos = 0
				self.update_underline(self.to_pos)
				return True
				
		return False


class ImageSoundStage(ListStage):
	titleimage = uiconfig.title_imagesound
	icon = uiconfig.image_sound_icon

	def __init__(self):
		self.title = _('IMAGES & SOUNDS')
		self.choice = _('Images'), _('Sounds'),  _('Videos'), _('Delete')
	
		ListStage.__init__(self)

	def activate(self, index):
		if index == 0:
			import images
			stage = images.ImagesStage
		elif index == 1:
			import sounds
			stage = sounds.SoundsStage
		elif index == 2:
			import videos
			stage = videos.VideosStage
		elif index == 3:
			stage = ImageSoundDeleteStage

		runtime.manager.stack_stage(stage)

_stages = MyAnnStage, PhoneBookStage, MessageStage, ServiceStage, MultimediaStage, SoundStage, ScreenStage, SettingStage

def get_stage(index):
	return _stages[index]