# -*- coding: UTF-8 -*-
#
#  $Id$
#
#-------------------------------------------------------
#
#              Foreca Weather Forecast E2
#
#   This Plugin retrieves the actual weather forecast
#   for the next 10 days from the Foreca website.
#
#        We wish all users wonderful weather!
#

VERSION = "3.2.11"
#
#                 07.08.2023
#
#     Source of information: https://www.foreca.it
#
#             Design and idea by
#                  @Bauernbub
#            enigma2 mod by mogli123
#
#-------------------------------------------------------
#
#  Provided with no warranties of any sort.
#
#-------------------------------------------------------
#
# History:
# 2.6 Various minor changes
# 2.7 Wrap around mode enabled in screen-lists
# 2.8 Calculate next date based on displayed date when left/right key is pushed
#	  after prior date jump using 0 - 9 keys was performed
# 2.9 Fix: Show correct date and time in weather videos
#     Main screen navigation modified to comply with standard usage:
#	  scroll page up/down by left/right key
#	  select previous/next day by left/right arrow key of numeric key group
# 2.9.1 Latvian cities and localization added. Thanks to muca
# 2.9.2 Iranian cities updated and localization added. Thanks to Persian Prince
#	Hungarian and Slovakian cities added. Thanks to torpe
# 2.9.3 Detail line in main screen condensed to show more text in SD screen
#	Grading of temperature colors reworked
#	Some code cosmetics
#	Translation code simplified: Setting the os LANGUAGE variable isn't needed anymore
#	Typos in German localization fixed
# 2.9.4 Many world-wide cities added. Thanks to AnodA
#	Hungarian and Slovakian localization added. Thanks to torpe
# 2.9.5 Fixed: Cities containing "_" didn't work as favorites. Thanks to kashmir
# 2.9.6 Size of temperature item slightly extended to match with skins using italic font
#	Grading of temperature colors reworked
# 2.9.7 Use specified "Frame size in full view" value when showing "5 day forecast" chart
#	Info screen reworked
#	False temperature colors fixed
#	Up/down keys now scroll by page in main screen (without highlighting selection)
# 3.0.0 Option added to select measurement units. Thanks to muca
#	Option added to select time format.
#	Setup menu reworked.
#	Main screen navigation modified: Select previous/next day by left/right key
#	Many Italian cities added and Italian localization updated. Thanks to mat8861
#	Czech, Greek, French, Latvian, Dutch, Polish, Russian localization updated. Thanks to muca
# 3.0.1 Fix broken transliteration
#	Disable selection in main screen.
# 3.0.2 Weather maps of Czech Republic, Greece, Hungary, Latvia, Poland, Russia, Slovakia added
#	Temperature Satellite video added
#	Control key assignment in slide show reworked to comply with Media Player standard
#	Some Italian cities added
#	Thumbnail folders compacted
#	Unused code removed, redundant code purged
#	Localization updated
# 3.0.3 List of German states and list of European countries sorted
#	Code cosmetics
#	Localization updated
# 3.0.4 Language determination improved
# 3.0.5 Setup of collating sequence reworked
# 3.0.6 Weather data in Russian version obtained from foreca.com instead of foreca.ru due
#	  to structural discrepancy of Russian web site
#	Code cosmetics
# 3.0.7 Turkish cities updated. Thanks to atsiz77
#	Debug state noted in log file
# 3.0.8 Fixed for Foreca's pages changes
# 3.0.9 Path for weather map regions updated after change of Wetterkontor's pages. Thanks to Bag58.
#	Add missing spinner icon
# 3.1.0 Plugin splitted into a loader and UI part, as Foreca needs quite a while to load. Hence
#	  actual load postponed until the user requests for it.
#	Finnish localization added. Thanks to kjuntara
#	Ukrainian localization added. Thanks to Irkoff
# 3.1.1 ForecaPreview skineable
# 3.1.2 Next screens skineable
# 3.1.3 Added font size for slideshow into setting
# 3.1.4 rem /www.metoffice.gov.uk due non existing infrared on this pages more
# 3.1.7 fix url foreca com
# 3.1.8 fix problem with national chars in favorite names
# 3.1.9 renamed parsed variables, added humidity into list - for display in default screen must be:
#	changed line:  		self.itemHeight = 90   ... change to new height, if is needed
#	and rearanged lines:	self.valText1 = 365,5,600,28
#				self.valText2 = 365,33,600,28
#				self.valText3 = 365,59,600,28
#				self.valText4 = 365,87,600,28
#	similar in user skin - there text4Pos="x,y,w,h" must be added
# 3.2.0	fixed satellite maps, removed infrared - page not exist more, sanity check if nothing is downloaded
# 3.2.3-r3 change URL to .net and .ru
# 3.2.6 Anpassungen an aktuelle Foreca Seite
# 3.2.7 Umstellung auf Foreca Seite .hr und Nutzung WebClientContextFactory für https
# 3.2.8 Skip to next/previous favorite city on left/right arrow key
#		Show home city (first entry of favorite list) on OK key press.
# 3.2.9 Support für WQHD-Screens im Universal-Image (One/Two/Seven)
#		fix SSL-Error on some boxes (re-add create_unverified_https_context)
# 3.2.11 Umstellung auf Foreca Seite .biz und Nutzung WebClientContextFactory für https
# Unresolved: Crash when scrolling in help screen of city panel
#
# To do:
#	
#	Show weather videos and maps on blue key
#	Show setup menu on Menu key


# for localized messages
from . import _
# GUI (Components)
from Components.ActionMap import ActionMap, NumberActionMap, HelpableActionMap
from Components.AVSwitch import AVSwitch
from Components.FileList import FileList
from Components.Label import Label
from Components.Button import Button
from Components.Sources.StaticText import StaticText
from Components.ScrollLabel import ScrollLabel
from Components.MenuList import MenuList
from Components.MultiContent import MultiContentEntryText, MultiContentEntryPixmapAlphaTest
from Components.Pixmap import Pixmap
from Components.PluginComponent import plugins
from Components.Console import Console
from Components.GUIComponent import GUIComponent
from skin import parseFont, parseColor, TemplatedListFonts, componentSizes

# Configuration
from Components.config import *
from Components.ConfigList import ConfigList, ConfigListScreen

# OS
import os

# Enigma
from enigma import eListboxPythonMultiContent, ePicLoad, eServiceReference, eTimer, getDesktop, gFont, RT_HALIGN_RIGHT, RT_HALIGN_LEFT, RT_VALIGN_CENTER

# Plugin definition
from Plugins.Plugin import PluginDescriptor

# GUI (Screens)
from Screens.ChoiceBox import ChoiceBox
from Screens.HelpMenu import HelpableScreen
from Screens.InfoBar import MoviePlayer
from Screens.Screen import Screen

# MessageBox
from Screens.MessageBox import MessageBox

# Timer
from time import *

from Tools.BoundFunction import boundFunction
from Tools.Directories import resolveFilename, SCOPE_LANGUAGE, SCOPE_CONFIG, SCOPE_PLUGINS, fileExists
from Tools.HardwareInfo import HardwareInfo
from Tools.LoadPixmap import LoadPixmap
from twisted.web.client import downloadPage, getPage

import htmlentitydefs, re, urllib2, urllib
from Components.Language import language
from re import sub, split, search, match, findall
import string
import locale
import sys
import threading

import ssl
try:
    _create_unverified_https_context = ssl._create_unverified_context
except AttributeError:
    pass
else:
    ssl._create_default_https_context = _create_unverified_https_context

PY3 = (sys.version_info[0] == 3)
if PY3:
    from urllib.request import urlopen, Request, pathname2url
else:
    from urllib import pathname2url
    from urllib2 import urlopen, Request

from twisted.internet.ssl import ClientContextFactory
from twisted.internet._sslverify import ClientTLSOptions
try:
    from urllib.parse import urlparse
except ImportError:
    from urlparse import urlparse

class WebClientContextFactory(ClientContextFactory):
    def __init__(self, url=None):
        domain = urlparse(url).netloc
        self.hostname = domain
    
    def getContext(self, hostname=None, port=None):
        ctx = ClientContextFactory.getContext(self)
        if self.hostname and ClientTLSOptions is not None: # workaround for TLS SNI
            ClientTLSOptions(self.hostname, ctx)
        return ctx

pluginPrintname = "[Foreca Ver. %s]" % VERSION
###############################################################################

config.plugins.foreca.resize = ConfigSelection(default="0", choices=[("0", _("simple")), ("1", _("better"))])
config.plugins.foreca.bgcolor = ConfigSelection(default="#00000000", choices=[("#00000000", _("black")), ("#009eb9ff", _("blue")), ("#00ff5a51", _("red")), ("#00ffe875", _("yellow")), ("#0038FF48", _("green"))])
config.plugins.foreca.textcolor = ConfigSelection(default="#0038FF48", choices=[("#00000000", _("black")), ("#009eb9ff", _("blue")), ("#00ff5a51", _("red")), ("#00ffe875", _("yellow")), ("#0038FF48", _("green"))])
config.plugins.foreca.framesize = ConfigInteger(default=5, limits=(5, 99))
config.plugins.foreca.fontsize = ConfigInteger(default=20, limits=(20, 30))
config.plugins.foreca.slidetime = ConfigInteger(default=1, limits=(1, 60))
config.plugins.foreca.infoline = ConfigYesNo(default=True)
config.plugins.foreca.loop = ConfigYesNo(default=False)
config.plugins.foreca.citylabels = ConfigEnableDisable(default=True)
config.plugins.foreca.units = ConfigSelection(default="metrickmh", choices=[("metric", _("Metric (C, m/s)")), ("metrickmh", _("Metric (C, km/h)")), ("imperial", _("Imperial (C, mph)")), ("us", _("US (F, mph)"))])
config.plugins.foreca.time = ConfigSelection(default="24h", choices=[("12h", _("12 h")), ("24h", _("24 h"))])
config.plugins.foreca.debug = ConfigEnableDisable(default=False)

HEADERS = {'User-Agent': 'Mozilla/5.0 (SmartHub; SMART-TV; U; Linux/SmartTV; Maple2012) AppleWebKit/534.7 (KHTML, like Gecko) SmartTV Safari/534.7'}
MAIN_PAGE = "https://www.foreca.it"
USR_PATH = resolveFilename(SCOPE_CONFIG)+"Foreca"
THUMB_PATH = resolveFilename(SCOPE_PLUGINS) + "Extensions/Foreca/thumb/"

deviceName = HardwareInfo().get_device_name()
DEBUG = config.plugins.foreca.debug.value

if DEBUG: print pluginPrintname, "Debug enabled"

else: print pluginPrintname, "Debug disabled"

# Make Path for Slideshow
CACHE_PATH = "/var/cache/Foreca/"
if os.path.exists(CACHE_PATH) is False:
    try:
        os.makedirs(CACHE_PATH, 755)
    except:
        pass

# Make Path for user settings
if os.path.exists(USR_PATH) is False:
    try:
        os.makedirs(USR_PATH, 755)
    except:
        pass

# Get screen size
size_w = getDesktop(0).size().width()
size_h = getDesktop(0).size().height()

# Get diacritics to handle
FILTERin = []
FILTERout = []
FILTERidx = 0

LANGUAGE = language.getActiveLanguage()[:2]

try:
    locale.setlocale(locale.LC_COLLATE, language.getLanguage())
except:
    print pluginPrintname, "Collating sequence undeterminable; default used"

if fileExists(USR_PATH + "/Filter.cfg"):
    file = open(USR_PATH + "/Filter.cfg", "r")
    for line in file:
        regel = str(line)
        if regel[:2] == LANGUAGE:
            if regel[4] == "Y":
                FILTERidx += 1
                FILTERin.append(regel[7:15].strip())
                FILTERout.append(regel[17:].strip())
    file.close

#---------------------- Skin Functions ----------------------------------------------------

def getScale():
    return AVSwitch().getFramebufferScale()

def calcSkinFactor(value=0):
    if size_w == 2560:
        return int(2 * value)
    elif size_w == 1920:
        return int(1.5 * value)
    else:
        return value

#------------------------------------------------------------------------------------------
#----------------------------------  MainMenuList   ---------------------------------------
#------------------------------------------------------------------------------------------


class MainMenuList(MenuList):
    SKIN_COMPONENT_KEY = "ForecaList"
    SKIN_COMPONENT_TEXT_HEIGHT = "textHeight"
    SKIN_COMPONENT_TEXT2_HEIGHT = "text2Height"
    SKIN_COMPONENT_TIME_WIDTH = "timeWidth"
    SKIN_COMPONENT_TIME_HEIGHT = "timeHeight"
    SKIN_COMPONENT_TEMP_WIDTH = "tempWidth"
    SKIN_COMPONENT_WIND_WIDTH = "windWidth"
    SKIN_COMPONENT_TEXT_WIDTH = "textWidth"
    SKIN_COMPONENT_TEXT2_WIDTH = "text2Width"
    SKIN_COMPONENT_ICON_HEIGHT = "iconHeight"
    SKIN_COMPONENT_ICON_WIDTH = "iconWidth"
    SKIN_COMPONENT_ICON_Y = "iconY"
    SKIN_COMPONENT_ICON2_HEIGHT = "icon2Height"
    SKIN_COMPONENT_ICON2_WIDTH = "icon2Width"
    SKIN_COMPONENT_ICON2_Y = "icon2Y"
    SKIN_COMPONENT_ICON3_HEIGHT = "icon3Height"
    SKIN_COMPONENT_ICON3_WIDTH = "icon3Width"
    SKIN_COMPONENT_TEXT_X = "textX"
    SKIN_COMPONENT_TEXT2_X = "text2X"
    SKIN_COMPONENT_TIME_X = "timeX"
    SKIN_COMPONENT_TEMP_X = "tempX"
    SKIN_COMPONENT_WIND_X = "windX"
    SKIN_COMPONENT_TEXT_Y = "textY"
    SKIN_COMPONENT_TEMP_Y = "tempY"
    SKIN_COMPONENT_WIND_Y = "windY"
    def __init__(self):
        MenuList.__init__(self, [], False, eListboxPythonMultiContent)
        tlf = TemplatedListFonts()
        self.l.setFont(0, gFont(tlf.face(tlf.BIG), tlf.size(tlf.BIG)))
        self.l.setFont(1, gFont(tlf.face(tlf.SMALL), tlf.size(tlf.SMALL)))
        self.l.setFont(2, gFont(tlf.face(tlf.MEDIUM), tlf.size(tlf.MEDIUM)))

        self.listCompleted = []
        self.callback = None
        self.idx = 0
        self.thumb = ""
        self.pos = 20
        print pluginPrintname, "MainMenuList..."


#--------------------------- Go through all list entries ----------------------------------
    def buildEntries(self):
        #if DEBUG: print pluginPrintname, "buildEntries:", len(self.list)
        if self.idx == len(self.list):
            self.setList(self.listCompleted)
            if self.callback:
                self.callback()
        else:
            self.downloadThumbnail()

    def downloadThumbnail(self):
        thumbUrl = self.list[self.idx][0]
        windDirection = self.list[self.idx][3]
        self.thumb = THUMB_PATH + str(thumbUrl + ".png")
        self.wind = THUMB_PATH + str(windDirection)
        self.buildEntry(None)

#----------------------------------- Build entries for list -------------------------------

    def buildEntry(self, picInfo=None):
        sizes = componentSizes[MainMenuList.SKIN_COMPONENT_KEY]
        timeWidth = sizes.get(MainMenuList.SKIN_COMPONENT_TIME_WIDTH, calcSkinFactor(70))
        timeHeight = sizes.get(MainMenuList.SKIN_COMPONENT_TIME_HEIGHT, calcSkinFactor(90))
        timeX = sizes.get(MainMenuList.SKIN_COMPONENT_TIME_X, calcSkinFactor(10))
        tempWidth = sizes.get(MainMenuList.SKIN_COMPONENT_TEMP_WIDTH, calcSkinFactor(80))
        tempX = sizes.get(MainMenuList.SKIN_COMPONENT_TEMP_X, calcSkinFactor(170))
        tempY = sizes.get(MainMenuList.SKIN_COMPONENT_TEMP_Y, calcSkinFactor(10))
        windWidth = sizes.get(MainMenuList.SKIN_COMPONENT_WIND_WIDTH, calcSkinFactor(100))
        windX = sizes.get(MainMenuList.SKIN_COMPONENT_WIND_X, calcSkinFactor(300))
        windY = sizes.get(MainMenuList.SKIN_COMPONENT_WIND_Y, calcSkinFactor(10))
        textWidth = sizes.get(MainMenuList.SKIN_COMPONENT_TEXT_WIDTH, calcSkinFactor(420))
        textX = sizes.get(MainMenuList.SKIN_COMPONENT_TEXT_X, calcSkinFactor(410))
        textY = sizes.get(MainMenuList.SKIN_COMPONENT_TEXT_Y, calcSkinFactor(30))
        textHeight = sizes.get(MainMenuList.SKIN_COMPONENT_TEXT_HEIGHT, calcSkinFactor(30))
        iconWidth = sizes.get(MainMenuList.SKIN_COMPONENT_ICON_WIDTH, calcSkinFactor(70))
        iconHeight = sizes.get(MainMenuList.SKIN_COMPONENT_ICON_HEIGHT, calcSkinFactor(70))
        iconY = sizes.get(MainMenuList.SKIN_COMPONENT_ICON_Y, calcSkinFactor(10))
        icon2Width = sizes.get(MainMenuList.SKIN_COMPONENT_ICON2_WIDTH, calcSkinFactor(30))
        icon2Height = sizes.get(MainMenuList.SKIN_COMPONENT_ICON2_HEIGHT, calcSkinFactor(30))
        icon2Y = sizes.get(MainMenuList.SKIN_COMPONENT_ICON2_Y, calcSkinFactor(25))
        self.x = self.list[self.idx]
        self.res = [(self.x[0], self.x[1])]

        violetred = 0xC7D285
        violet = 0xff40b3
        gruen = 0x77f424
        dgruen = 0x53c905
        drot = 0xff4040
        rot = 0xff6640
        orange = 0xffb340
        gelb = 0xffff40
        ddblau = 0x3b62ff
        dblau = 0x408cff
        mblau = 0x40b3ff
        blau = 0x40d9ff
        hblau = 0x40ffff
        weiss = 0xffffff

        if config.plugins.foreca.units.value == "us":
            self.centigrades = round((int(self.x[2]) - 32) / 1.8)
            tempUnit = _("°F")
        else:
            self.centigrades = int(self.x[2])
            tempUnit = _("°C")
        if self.centigrades <= -20:
            self.tempcolor = ddblau
        elif self.centigrades <= -15:
            self.tempcolor = dblau
        elif self.centigrades <= -10:
            self.tempcolor = mblau
        elif self.centigrades <= -5:
            self.tempcolor = blau
        elif self.centigrades <= 0:
            self.tempcolor = hblau
        elif self.centigrades < 5:
            self.tempcolor = dgruen
        elif self.centigrades < 10:
            self.tempcolor = gruen
        elif self.centigrades < 15:
            self.tempcolor = gelb
        elif self.centigrades < 20:
            self.tempcolor = orange
        elif self.centigrades < 25:
            self.tempcolor = rot
        elif self.centigrades < 30:
            self.tempcolor = drot
        else:
            self.tempcolor = violet

        # Time
        self.res.append(MultiContentEntryText(pos=(timeX, 0), size=(timeWidth, timeHeight), font=0, flags=RT_HALIGN_LEFT|RT_VALIGN_CENTER, text=self.x[1], color=weiss, color_sel=weiss))

        # forecast pictogram
        pngpic = LoadPixmap(self.thumb)
        if pngpic is not None:
            self.res.append(MultiContentEntryPixmapAlphaTest(pos=(timeX + timeWidth , iconY), size=(iconWidth, iconHeight), png=pngpic))

        # Temp
        self.res.append(MultiContentEntryText(pos=(tempX, tempY), size=(tempWidth, textHeight), font=0, text=_("Temp"), color=weiss, color_sel=weiss))

        self.res.append(MultiContentEntryText(pos=(tempX, tempY*4), size=(tempWidth, textHeight), font=2, text=self.x[2] + tempUnit, color=self.tempcolor, color_sel=self.tempcolor))

        # wind pictogram
        pngpic = LoadPixmap(self.wind + ".png")
        if pngpic is not None:
            self.res.append(MultiContentEntryPixmapAlphaTest(pos=(tempX + tempWidth , icon2Y), size=(icon2Width, icon2Height), png=pngpic))

        # Wind
        self.res.append(MultiContentEntryText(pos=(windX, windY), size=(windWidth, textHeight), font=0, text=_("Wind"), color=weiss, color_sel=weiss))

        self.res.append(MultiContentEntryText(pos=(windX, windY*4), size=(windWidth, textHeight), font=2, text=self.x[4], color=violetred, color_sel=violetred))

        # Text
        self.res.append(MultiContentEntryText(pos=(textX, 0), size=(textWidth, textHeight), font=0, flags=RT_HALIGN_LEFT|RT_VALIGN_CENTER, text=self.x[5], color=weiss, color_sel=weiss))

        textsechs=self.x[6]
        textsechs=textsechs.replace("&deg;", "") + tempUnit
        self.res.append(MultiContentEntryText(pos=(textX, textY), size=(textWidth, textHeight), font=1, text=textsechs, color=mblau, color_sel=mblau))

        self.res.append(MultiContentEntryText(pos=(textX, textY*1.8), size=(textWidth, textHeight), font=1, text=self.x[7], color=mblau, color_sel=mblau))

        self.res.append(MultiContentEntryText(pos=(textX, textY*2.6), size=(textWidth, textHeight), font=1, text=self.x[8], color=mblau, color_sel=mblau))

        self.listCompleted.append(self.res)
        self.idx += 1
        self.buildEntries()

# -------------------------- Build Menu list ----------------------------------------------

    def SetList(self, l):

        if DEBUG: print pluginPrintname, "SetList"
        self.list = l
        itemHeight = calcSkinFactor(componentSizes.itemHeight(self.SKIN_COMPONENT_KEY, 120))
        self.l.setItemHeight(itemHeight)
        del self.listCompleted
        self.listCompleted = []
        self.idx = 0
        self.buildEntries()

#------------------------------------------------------------------------------------------
#------------------------------------------ Spinner ---------------------------------------
#------------------------------------------------------------------------------------------

class ForecaPreviewCache(Screen):

    if size_w == 1920:
        skin = """
        <screen position="1450,95" size="60,60" backgroundColor="transparent" flags="wfNoBorder" zPosition="100" >
            <widget name="spinner" position="0,0" size="60,60"/>
        </screen>"""
    elif size_w == 2560:
        skin = """
        <screen position="center,center" size="152,152" backgroundColor="transparent" flags="wfNoBorder" zPosition="100">
            <widget name="spinner" position="28,28" size="96,96"/>
        </screen>"""
    else:
        skin = """
        <screen position="center,center" size="76,76" backgroundColor="transparent" flags="wfNoBorder" zPosition="100">
            <widget name="spinner" position="14,14" size="48,48"/>
        </screen>"""

    def __init__(self, session):
        self.session = session
        Screen.__init__(self, session)

        self["spinner"] = Pixmap()
        self.curr = 0

        self.timer = eTimer()
        if os.path.exists("/var/lib/dpkg/status"):
            self.timer_conn = self.timer.timeout.connect(self.showNextSpinner)
        else:
            self.timer.callback.append(self.showNextSpinner)

    def start(self):
        self.show()
        self.timer.start(120, False)

    def stop(self):
        self.hide()
        self.timer.stop()

    def showNextSpinner(self):
        self.curr += 1
        if self.curr > 3:
            self.curr = 0
        png = LoadPixmap(cached=True, path=PICON_PATH + str(self.curr) + ".png")
        self["spinner"].instance.setPixmap(png)

#------------------------------------------------------------------------------------------
#------------------------------ Foreca Preview---------------------------------------------
#------------------------------------------------------------------------------------------

class ForecaPreview(Screen, HelpableScreen):

    def __init__(self, session):
        global MAIN_PAGE, menu
        self.session = session
        MAIN_PAGE = "https://www.foreca.it"

        # actual, local Time as Tuple
        lt = localtime()
        # Extract the Tuple, Date
        jahr, monat, tag = lt[0:3]
        heute = "%04i%02i%02i" % (jahr, monat, tag)
        if DEBUG: print pluginPrintname, "determined local date:", heute
        self.tag = 0

        # Get favorites
        global fav1, fav2, fav1_city, fav2_city
        if fileExists(USR_PATH + "/fav1.cfg"):
            file = open(USR_PATH + "/fav1.cfg", "r")
            fav1 = str(file.readline().strip())
            fav1_city = fav1
            file.close()
            fav1 = fav1[fav1.rfind("/") + 1:len(fav1)]
        else:
            fav1_city = "United_States/New_York_City"
            fav1 = "New_York_City"
        print pluginPrintname, "fav1 location:", fav1
        
        if fileExists(USR_PATH + "/fav2.cfg"):
            file = open(USR_PATH + "/fav2.cfg", "r")
            fav2 = str(file.readline().strip())
            fav2_city = fav2
            file.close()
            fav2 = fav2[fav2.rfind("/") + 1:len(fav2)]
        else:
            fav2_city = "Russia/Moskva"
            fav2 = "Moskva"
        print pluginPrintname, "fav2 location:", fav2

        # Get home location
        global city, start, start_city
        if fileExists(USR_PATH + "/startservice.cfg"):
            file = open(USR_PATH + "/startservice.cfg", "r")
            self.ort = str(file.readline().strip())
            file.close()
            start = self.ort[self.ort.rfind("/") + 1:len(self.ort)]
        else:
            self.ort = "United_Kingdom/London"
            start = "London"
        start_city = self.ort
        print pluginPrintname, "home location:", self.ort

        MAIN_PAGE = "https://www.foreca.it" + "/" + urllib.pathname2url(self.ort) + "?lang=" + LANGUAGE + "&details=" + heute + "&units=" + config.plugins.foreca.units.value +"&tf=" + config.plugins.foreca.time.value
        print pluginPrintname, "initial link:" , MAIN_PAGE

        if size_w == 1920:
            self.skin = """
                <screen name="ForecaPreview" position="center,170" size="1200,820" title="Foreca Weather Forecast" >
                    <ePixmap pixmap="skin_default/buttons/red.png" position="10,5" size="295,70" />
                    <ePixmap pixmap="skin_default/buttons/green.png" position="305,5" size="295,70" />
                    <ePixmap pixmap="skin_default/buttons/yellow.png" position="600,5" size="295,70" />
                    <ePixmap pixmap="skin_default/buttons/blue.png" position="895,5" size="295,70" />
                    <widget backgroundColor="#9f1313" font="Regular;30" halign="center" position="10,5" render="Label" shadowColor="black" shadowOffset="-2,-2" size="295,70" source="key_red" transparent="1" valign="center" zPosition="1" />
                    <widget backgroundColor="#1f771f" font="Regular;30" halign="center" position="305,5" render="Label" shadowColor="black" shadowOffset="-2,-2" size="295,70" source="key_green" transparent="1" valign="center" zPosition="1" />
                    <widget backgroundColor="#a08500" font="Regular;30" halign="center" position="600,5" render="Label" shadowColor="black" shadowOffset="-2,-2" size="295,70" source="key_yellow" transparent="1" valign="center" zPosition="1" />
                    <widget backgroundColor="#18188b" font="Regular;30" halign="center" position="895,5" render="Label" shadowColor="black" shadowOffset="-2,-2" size="295,70" source="key_blue" transparent="1" valign="center" zPosition="1" />
                                               
                    <eLabel backgroundColor="grey" position="10,80" size="1180,1" />
                    <widget backgroundColor="background" source="Titel" render="Label" position="10,90" size="1180,40" foregroundColor="yellow" font="Regular;32" halign="center" transparent="1"/>
                    <widget backgroundColor="background" source="Titel2" render="Label" position="10,90" size="1180,40" font="Regular;32" halign="center" transparent="1"/>
                    <widget name="MainList" position="10,160" size="1180,600" enableWrapAround="1" scrollbarMode="showOnDemand" />
                    <eLabel backgroundColor="grey" position="10,770" size="1180,1" />
                    <ePixmap position="10,780" size="60,30" pixmap="skin_default/icons/info.png" />
                    <ePixmap position="360,780" size="60,30" pixmap="skin_default/icons/menu.png" />
                    <ePixmap position="710,780" size="60,30" pixmap="/usr/lib/enigma2/python/Plugins/Extensions/Foreca/buttons/key_ok.png" />
                    <widget source="key_info" render="Label" position="90,780" size="250,35" font="Regular;30" />
                    <widget source="key_menu" render="Label" position="440,780" size="250,35" font="Regular;30" />
                    <widget source="key_ok" render="Label" position="790,780" size="250,35" font="Regular;30" />
                    <ePixmap position="1120,780" size="60,30" pixmap="skin_default/icons/help.png" />
                </screen>"""
        elif size_w == 2560:
            self.skin = """
                <screen name="ForecaPreview" position="center,240" size="1640,1040" title="Foreca Weather Forecast" >
                    <ePixmap pixmap="skin_default/buttons/red.png" position="20,10" size="400,80" />
                    <ePixmap pixmap="skin_default/buttons/green.png" position="420,10" size="400,80" />
                    <ePixmap pixmap="skin_default/buttons/yellow.png" position="820,10" size="400,80" />
                    <ePixmap pixmap="skin_default/buttons/blue.png" position="1220,10" size="400,80" />
                    <widget source="key_red" render="Label" position="20,10" size="400,80" zPosition="1" font="Regular;40" halign="center" valign="center" backgroundColor="#9f1313" transparent="1" shadowColor="black" shadowOffset="-2,-2" />
                             
                    <widget source="key_green" render="Label" position="420,10" size="400,80" zPosition="1" font="Regular;40" halign="center" valign="center" backgroundColor="#1f771f" transparent="1" shadowColor="black" shadowOffset="-2,-2" />
                    <widget source="key_yellow" render="Label" position="820,10" size="400,80" zPosition="1" font="Regular;40" halign="center" valign="center" backgroundColor="#a08500" transparent="1" shadowColor="black" shadowOffset="-2,-2" />
                    <widget source="key_blue" render="Label" position="1220,10" size="400,80" zPosition="1" font="Regular;40" halign="center" valign="center" backgroundColor="#18188b" transparent="1" shadowColor="black" shadowOffset="-2,-2" />
                    <eLabel position="20,100" size="1600,2" backgroundColor="grey" />
                    <widget backgroundColor="background" source="Titel" render="Label" position="20,110" size="1600,100" font="Regular;44" valign="center" halign="center" transparent="1"/>
                    <widget backgroundColor="background" source="Titel2" render="Label" position="20,110" size="1600,100" font="Regular;44" valign="center" halign="center" transparent="1"/>
                    <widget name="MainList" position="20,220" size="1600,720" enableWrapAround="1" scrollbarMode="showOnDemand" />
                    <eLabel position="20,960" size="1600,2" backgroundColor="grey" />
                    <ePixmap position="20,980" size="100,50" pixmap="skin_default/buttons/key_info.png" />
                    <ePixmap position="460,980" size="100,50" pixmap="skin_default/buttons/key_menu.png" />
                    <ePixmap position="900,980" size="100,50" pixmap="/usr/lib/enigma2/python/Plugins/Extensions/Foreca/buttons/key_ok.png" />
                    <widget source="key_info" render="Label" position="140,980" size="320,50" font="Regular;44" />
                    <widget source="key_menu" render="Label" position="580,980" size="320,50" font="Regular;44" />
                    <widget source="key_ok" render="Label" position="1020,980" size="320,50" font="Regular;44" />
                    <ePixmap position="1500,980" size="100,50" pixmap="/usr/lib/enigma2/python/Plugins/Extensions/Foreca/buttons/key_help.png" />
                </screen>"""
        else:
            self.skin = """
                <screen name="ForecaPreview" position="center,120" size="820,520" title="Foreca Weather Forecast" >
                    <ePixmap pixmap="skin_default/buttons/red.png" position="10,5" size="200,40" />
                    <ePixmap pixmap="skin_default/buttons/green.png" position="210,5" size="200,40" />
                    <ePixmap pixmap="skin_default/buttons/yellow.png" position="410,5" size="200,40" />
                    <ePixmap pixmap="skin_default/buttons/blue.png" position="610,5" size="200,40" />
                    <widget source="key_red" render="Label" position="10,5" size="200,40" zPosition="1" font="Regular;20" halign="center" valign="center" backgroundColor="#9f1313" transparent="1" shadowColor="black" shadowOffset="-2,-2" />
                             
                    <widget source="key_green" render="Label" position="210,5" size="200,40" zPosition="1" font="Regular;20" halign="center" valign="center" backgroundColor="#1f771f" transparent="1" shadowColor="black" shadowOffset="-2,-2" />
                    <widget source="key_yellow" render="Label" position="410,5" size="200,40" zPosition="1" font="Regular;20" halign="center" valign="center" backgroundColor="#a08500" transparent="1" shadowColor="black" shadowOffset="-2,-2" />
                    <widget source="key_blue" render="Label" position="610,5" size="200,40" zPosition="1" font="Regular;20" halign="center" valign="center" backgroundColor="#18188b" transparent="1" shadowColor="black" shadowOffset="-2,-2" />
                    <eLabel position="10,50" size="800,1" backgroundColor="grey" />
                    <widget backgroundColor="background" source="Titel" render="Label" position="10,55" size="800,50" font="Regular;22" valign="center" halign="center" transparent="1"/>
                    <widget backgroundColor="background" source="Titel2" render="Label" position="10,55" size="800,50" font="Regular;22" valign="center" halign="center" transparent="1"/>
                    <widget name="MainList" position="10,110" size="800,360" enableWrapAround="1" scrollbarMode="showOnDemand" />
                    <eLabel position="10,480" size="800,1" backgroundColor="grey" />
                    <ePixmap position="10,490" size="50,25" pixmap="skin_default/buttons/key_info.png" />
                    <ePixmap position="230,490" size="50,25" pixmap="skin_default/buttons/key_menu.png" />
                    <ePixmap position="450,490" size="50,25" pixmap="/usr/lib/enigma2/python/Plugins/Extensions/Foreca/buttons/key_ok.png" />
                    <widget source="key_info" render="Label" position="70,490" size="160,25" font="Regular;22" />
                    <widget source="key_menu" render="Label" position="290,490" size="160,25" font="Regular;22" />
                    <widget source="key_ok" render="Label" position="510,490" size="160,25" font="Regular;22" />
                    <ePixmap position="750,490" size="50,25" pixmap="/usr/lib/enigma2/python/Plugins/Extensions/Foreca/buttons/key_help.png" />
                </screen>"""

        Screen.__init__(self, session)
        self.setup_title = _("Foreca Weather Forecast")
        self["MainList"] = MainMenuList()
        self["Titel"] = StaticText()
        self["Titel2"] = StaticText(_("Please wait ..."))
        self["Titel3"] = StaticText()
        self["Titel4"] = StaticText()
        self["Titel5"] = StaticText()
        self["key_red"] = StaticText(_("Forecast 5 days"))
        self["key_ok"] = StaticText(_("City"))
        if config.plugins.foreca.citylabels.value == True:
            self["key_green"] = StaticText(string.replace(fav1, "_", " "))
            self["key_yellow"] = StaticText(string.replace(fav2, "_", " "))
            self["key_blue"] = StaticText(string.replace(start, "_", " "))
        else:
            self["key_green"] = StaticText(_("Favorite 1"))
            self["key_yellow"] = StaticText(_("Favorite 2"))
            self["key_blue"] = StaticText(_("Home"))
        self["key_info"] = StaticText(_("Legend"))
        self["key_menu"] = StaticText(_("Maps"))
        self["Title"] = StaticText(_("Foreca Weather Forecast") + "   " + _("DreamOS Version ") + VERSION)

        HelpableScreen.__init__(self)
        self["actions"] = HelpableActionMap(self, "ForecaActions",
            {
                "cancel": (self.exit, _("Exit - End")),
                "menu": (self.Menu, _("Menu - Weather maps")),
                "showEventInfo": (self.info, _("Info - Legend")),
                "ok": (self.OK, _("OK - City")),
                "left": (self.left, _("Left - Previous day")),
                "right": (self.right, _("Right - Next day")),
                "up": (self.up, _("Up - Previous page")),
                "down": (self.down, _("Down - Next page")),
                "previous": (self.previous, _("Left arrow - Previous day")),
                "next": (self.next, _("Right arrow - Next day")),
                "red": (self.red, _("Red - Forecast 5 days")),
                #"shift_red": (self.shift_red, _("Red long - 10 day forecast")),
                "green": (self.Fav1, _("Green - Favorite 1")),
                "yellow": (self.Fav2, _("Yellow - Favorite 2")),
                "blue": (self.Fav0, _("Blue - Home")),
                "0": (boundFunction(self.keyNumberGlobal,0), _("0 - Today")),
                "1": (boundFunction(self.keyNumberGlobal,1), _("1 - Today + 1 day")),
                "2": (boundFunction(self.keyNumberGlobal,2), _("2 - Today + 2 days")),
                "3": (boundFunction(self.keyNumberGlobal,3), _("3 - Today + 3 days")),
                "4": (boundFunction(self.keyNumberGlobal,4), _("4 - Today + 4 days")),
                "5": (boundFunction(self.keyNumberGlobal,5), _("5 - Today + 5 days")),
                "6": (boundFunction(self.keyNumberGlobal,6), _("6 - Today + 6 days")),
                "7": (boundFunction(self.keyNumberGlobal,7), _("7 - Today + 7 days")),
                "8": (boundFunction(self.keyNumberGlobal,8), _("8 - Today + 8 days")),
                "9": (boundFunction(self.keyNumberGlobal,9), _("9 - Today + 9 days")),
            }, -2)

        self.StartPageFirst()

    def StartPageFirst(self):
        print pluginPrintname, "StartPageFirst..."
        self.cacheDialog = self.session.instantiateDialog(ForecaPreviewCache)
        self["MainList"].callback = self.deactivateCacheDialog
        self.working = False
        self["MainList"].show
        self.cacheTimer = eTimer()
        self.cacheDialog.start()
        self.onLayoutFinish.append(self.getPage)

    def StartPage(self):
        self["Titel"].text = ""
        self["Titel3"].text = ""
        self["Titel4"].text = ""
        self["Titel5"].text = ""
        self["Titel2"].text = _("Please wait ...")
        self.working = False
        print pluginPrintname, "MainList show..."
        self["MainList"].show
        self.getPage()

    def getPage(self, page=None):
        print pluginPrintname, "getPage..."
        self.cacheDialog.start()
        self.working = True
        if not page:
            page = ""
        url = "%s%s"%(MAIN_PAGE, page)
        print pluginPrintname, "page link:" , url
        contextFactory = WebClientContextFactory(url)
        getPage(url,contextFactory=contextFactory).addCallback(self.getForecaPage).addErrback(self.error)

    def error(self, err=""):
        print pluginPrintname, "Error:", err
        self.working = False
        self.deactivateCacheDialog()

    def deactivateCacheDialog(self):
        self.cacheDialog.stop()
        self.working = False

    def exit(self):
        try:
            os.unlink("/tmp/sat.jpg")
        except:
            pass

        try:
            os.unlink("/tmp/sat.html")
        except:
            pass

        try:
            os.unlink("/tmp/meteogram.png")
        except:
            pass

        self.close()
        self.deactivateCacheDialog()

    def keyNumberGlobal(self, number):
        self.tag = number
        self.Zukunft(self.tag)

    def Fav0(self):
        print pluginPrintname, "home location:", start_city
        self.ort = start_city
        self.tag = 0
        self.Zukunft(0)

    def Fav1(self):
        print pluginPrintname, "fav1 location:", fav1_city
        self.ort = fav1_city
        self.tag = 0
        self.Zukunft(0)

    def Fav2(self):
        print pluginPrintname, "fav2 location:", fav2_city
        self.ort = fav2_city
        self.tag = 0
        self.Zukunft(0)

    def Zukunft(self, ztag=0):
        global MAIN_PAGE
        # actual, local Time as Tuple
        lt = localtime()
        jahr, monat, tag = lt[0:3]

        # Calculate future date
        ntag = tag + ztag
        zukunft = jahr, monat, ntag, 0, 0, 0, 0, 0, 0
        morgen = mktime(zukunft)
        lt = localtime(morgen)
        jahr, monat, tag = lt[0:3]
        morgen = "%04i%02i%02i" % (jahr, monat, tag)

        MAIN_PAGE = "https://www.foreca.it" + "/" + urllib.pathname2url(self.ort) + "?lang=" + LANGUAGE + "&details=" + morgen + "&units=" + config.plugins.foreca.units.value + "&tf=" + config.plugins.foreca.time.value
        print pluginPrintname, "day link:", MAIN_PAGE

        # Show in GUI
        self.StartPage()

    def info(self):
        message = "%s" % (_("<|   |>           =   Prognosis Next/Previous day\n0 - 9            =   Prognosis (x) days from now\n\nKey 7 | 9   =   Fast scroll 500 (City choice)\nKey < | >   =   Fast scroll 100 (City choice)\n\nInfo              =   This information\nMenu           =   Satellite photos and maps\n\nRed              =   Forecasting chart for the next 5 days\nGreen          =   Go to Favorite 1\nYellow         =   Go to Favorite 2\nBlue             =   Go to Home\n\nWind direction  =  Arrow to right: Wind from the West"))
        self.session.open( MessageBox, message, MessageBox.TYPE_INFO)

    def OK(self):
        global city
        panelmenu = ""
        city = self.ort
        self.session.openWithCallback(self.OKCallback, CityPanel, panelmenu)

    def OKCallback(self):
        global city, fav1, fav2
        self.ort = city
        self.tag = 0
        self.Zukunft(0)
        if config.plugins.foreca.citylabels.value == True:
            self["key_green"].setText(string.replace(fav1, "_", " "))
            self["key_yellow"].setText(string.replace(fav2, "_", " "))
            self["key_blue"].setText(string.replace(start, "_", " "))
        else:
            self["key_green"].setText(_("Favorite 1"))
            self["key_yellow"].setText(_("Favorite 2"))
            self["key_blue"].setText(_("Home"))
        print pluginPrintname, "MenuCallback"

    def left(self):
        if not self.working and self.tag >= 1:
            self.tag = self.tag - 1
            self.Zukunft(self.tag)

    def right(self):
        if not self.working and self.tag < 9:
            self.tag = self.tag + 1
            self.Zukunft(self.tag)

    def up(self):
        if not self.working:
            self["MainList"].pageUp()

    def down(self):
        if not self.working:
            self["MainList"].pageDown()

    def previous(self):
        if self.ort == start_city:
            self.ort = fav2_city
        elif self.ort == fav2_city:
            self.ort = fav1_city
        else:
            self.ort = start_city
        self.Zukunft(self.tag)

    def next(self):
        if self.ort == start_city:
            self.ort = fav1_city
        elif self.ort == fav1_city:
            self.ort = fav2_city
        else:
            self.ort = start_city
        self.Zukunft(self.tag)

    def red(self):
        if not self.working:
            #/meteogram.php?loc_id=211001799&amp;mglang=de&amp;units=metrickmh&amp;tf=24h
            self.url = "https://www.foreca.it" + "/meteogram.php?loc_id=" + self.loc_id + "&mglang=" + LANGUAGE + "&units=" + config.plugins.foreca.units.value + "&tf=" + config.plugins.foreca.time.value + "/meteogram.png"
            print self.url
            self.loadPicture(self.url)

    def shift_red(self):
        pass
        #self.session.openWithCallback(self.MenuCallback, Foreca10Days, self.ort)

    def Menu(self):
        self.session.openWithCallback(self.MenuCallback, SatPanel, self.ort)

    def MenuCallback(self):
        global menu, start, fav1, fav2
        if config.plugins.foreca.citylabels.value == True:
            self["key_green"].setText(string.replace(fav1, "_", " "))
            self["key_yellow"].setText(string.replace(fav2, "_", " "))
            self["key_blue"].setText(string.replace(start, "_", " "))
        else:
            self["key_green"].setText(_("Favorite 1"))
            self["key_yellow"].setText(_("Favorite 2"))
            self["key_blue"].setText(_("Home"))

    def loadPicture(self, url=""):
        devicepath = "/tmp/meteogram.png"
        req = Request(url, headers=HEADERS)
        resp = urlopen(req, timeout=2)
        with open(devicepath, 'wb') as f:
            f.write(resp.read())
        self.session.open(PicView, devicepath, 0, False)

    def getForecaPage(self, html):
        #new Ajax.Request('/lv?id=102772400', {
        fulltext = re.compile(r"id: '(.*?)'", re.DOTALL)
        id = fulltext.findall(html)

        if DEBUG: print pluginPrintname, "fulltext=", fulltext, "id=", id
        self.loc_id = str(id[0])

        # <!-- START -->
        #<h6><span>Tuesday</span> March 29</h6>

        if DEBUG: print pluginPrintname, "Start:" + str(len(html))
        fulltext = re.compile(r'<!-- START -->.+?<h6><span>(.+?)</h6>', re.DOTALL)
        titel = fulltext.findall(html)

        if DEBUG: print pluginPrintname, "fulltext=", fulltext, "titel=", titel
        titel[0] = str(sub('<[^>]*>',"",titel[0]))

        if DEBUG: print pluginPrintname, "titel[0]=", titel[0]

        # <a href="/Austria/Linz?details=20110330">We</a>
        fulltext = re.compile(r'<!-- START -->(.+?)<h6>', re.DOTALL)
        link = str(fulltext.findall(html))
        #print link

        fulltext = re.compile(r'<a href=".+?>(.+?)<.+?', re.DOTALL)
        tag = str(fulltext.findall(link))
        #print "Day ", tag

        # ---------- Wetterdaten -----------

        # <div class="row clr0">
        fulltext = re.compile(r'<!-- START -->(.+?)<div class="datecopy">', re.DOTALL)
        html = str(fulltext.findall(html))

        print(pluginPrintname, "searching .....")
        list = []

        fulltext = re.compile(r'<a href="(.+?)".+?', re.DOTALL)
        taglink = str(fulltext.findall(html))
        #taglink = konvert_uml(taglink)
        if DEBUG: print pluginPrintname, "Daylink ", taglink

        fulltext = re.compile(r'<a href=".+?>(.+?)<.+?', re.DOTALL)
        tag = fulltext.findall(html)

        if DEBUG: print pluginPrintname,  "Day", str(tag)

        # <div class="c0"> <strong>17:00</strong></div>
        fulltime = re.compile(r'<div class="c0"> <strong>(.+?)<.+?', re.DOTALL)
        zeit = fulltime.findall(html)

        if DEBUG: print pluginPrintname,  "Time", str(zeit)

        #<div class="c4">
        #<span class="warm"><strong>+15&deg;</strong></span><br />
        fulltime = re.compile(r'<div class="c4">.*?<strong>(.+?)&.+?', re.DOTALL)
        temp = fulltime.findall(html)

        if DEBUG: print pluginPrintname,  "Temp", str(temp)

        # <div class="symbol_50x50d symbol_d000_50x50" title="clear"
        fulltext = re.compile(r'<div class="symbol_50x50.+? symbol_(.+?)_50x50.+?', re.DOTALL)
        thumbnails = fulltext.findall(html)

        fulltext = re.compile(r'<div class="c3">.+? (.+?)<br />.+?', re.DOTALL)
        description = fulltext.findall(html)

        if DEBUG: print pluginPrintname,  "description", str(description).lstrip("\t").lstrip()

        fulltext = re.compile(r'<div class="c3">.+?<br />(.+?)</strong>.+?', re.DOTALL)
        feels = fulltext.findall(html)

        if DEBUG: print pluginPrintname,  "feels", str(feels).lstrip("\t").lstrip()

        fulltext = re.compile(r'<div class="c3">.+?</strong><br />(.+?)</.+?', re.DOTALL)
        precip = fulltext.findall(html)

        if DEBUG: print pluginPrintname,  "precip" , str(precip).lstrip("\t").lstrip()

        fulltext = re.compile(r'<div class="c3">.+?</strong><br />.+?</strong><br />(.+?)</', re.DOTALL)
        humidity = fulltext.findall(html)

        if DEBUG: print pluginPrintname,  "humidity" , str(humidity).lstrip("\t").lstrip()

        fulltext = re.compile(r'<div class="c2">.+?<img src="//img-b.foreca.net/s/symb-wind/(.+?).gif', re.DOTALL)
        windDirection = fulltext.findall(html)

        if DEBUG: print pluginPrintname,  "windDirection", str(windDirection)

        fulltext = re.compile(r'<div class="c2">.+?<strong>(.+?)<.+?', re.DOTALL)
        windSpeed = fulltext.findall(html)

        if DEBUG: print pluginPrintname,  "windSpeed", str(windSpeed)

        timeEntries = len(zeit)
        #print("Aantal tijden ", str(timeEntries))
        x = 0
        while x < timeEntries:
            description[x] = self.konvert_uml(str(sub('<[^>]*>',"",description[x])))
            feels[x] = self.konvert_uml(str(sub('<[^>]*>',"",feels[x])))
            precip[x] = self.konvert_uml(str(sub('<[^>]*>',"",precip[x])))
            humidity[x] = self.konvert_uml(str(sub('<[^>]*>',"",humidity[x])))
            windSpeed[x] = self.filter_dia(windSpeed[x])
            if DEBUG: print pluginPrintname, "weather:", zeit[x], temp[x], windDirection[x], windSpeed[x], description[x], feels[x] , precip[x], humidity[x]
            list.append([thumbnails[x], zeit[x], temp[x], windDirection[x], windSpeed[x], description[x], feels[x], precip[x], humidity[x]])
            x += 1

        self["Titel2"].text = ""
        datum = titel[0]
        foundPos=datum.rfind(" ")
        foundPos2=datum.find(" ")
        datum2=datum[:foundPos2]+datum[foundPos:]+"."+datum[foundPos2:foundPos]
        foundPos=self.ort.find("/")
        plaats=_(self.ort[0:foundPos]) + "-" + self.ort[foundPos+1:len(self.ort)]
        self["Titel"].text = string.replace(plaats, "_", " ") + "  -  " + datum2
        self["Titel4"].text = string.replace(plaats, "_", " ")
        self["Titel5"].text = datum2
        self["Titel3"].text = string.replace(self.ort[:foundPos], "_", " ") + "\r\n" + string.replace(self.ort[foundPos+1:], "_", " ") + "\r\n" + datum2
        self["MainList"].SetList(list)
        self["MainList"].selectionEnabled(0)
        self["MainList"].show

#---------------------- Diacritics Function -----------------------------------------------

    def filter_dia(self, text):
        # remove diacritics for selected language
        filterItem = 0
        while filterItem < FILTERidx:
            text = string.replace(text, FILTERin[filterItem], FILTERout[filterItem])
            filterItem += 1
        return text

    def konvert_uml(self, text):
        text = self.filter_dia(text)
        # remove remaining control characters and return
        return text[text.rfind("\\t") + 2:len(text)]

#------------------------------------------------------------------------------------------
#------------------------------ City Panel ------------------------------------------------
#------------------------------------------------------------------------------------------

class CityPanelList(MenuList):
    def __init__(self, list):
        MenuList.__init__(self, [], False, eListboxPythonMultiContent)
        tlf = TemplatedListFonts()
        self.l.setFont(0, gFont(tlf.face(tlf.BIGGER), tlf.size(tlf.BIGGER)))

# -------------------------------------------------------------------

class CityPanel(Screen, HelpableScreen):

    def __init__(self, session, panelmenu):
        self.session = session

        if size_w == 1920:
            self.skin = """
            <screen name="CityPanel" position="center,170" size="1200,820" title="Select a city" >
                <ePixmap pixmap="skin_default/buttons/green.png" position="10,5" scale="stretch" size="390,70" />
                <ePixmap pixmap="skin_default/buttons/yellow.png" position="405,5" scale="stretch" size="390,70" />
                <ePixmap pixmap="skin_default/buttons/blue.png" position="800,5" scale="stretch" size="390,70" />
                <widget backgroundColor="#1f771f" font="Regular;30" halign="center" position="10,5" render="Label" shadowColor="black" shadowOffset="-2,-2" size="390,70" source="key_green" transparent="1" valign="center" zPosition="1" />
                <widget backgroundColor="#a08500" font="Regular;30" halign="center" position="405,5" render="Label" shadowColor="black" shadowOffset="-2,-2" size="390,70" source="key_yellow" transparent="1" valign="center" zPosition="1" />
                <widget backgroundColor="#18188b" font="Regular;30" halign="center" position="800,5" render="Label" shadowColor="black" shadowOffset="-2,-2" size="390,70" source="key_blue" transparent="1" valign="center" zPosition="1" />
                <eLabel backgroundColor="grey" position="10,80" size="1180,1" />
                <widget name="Mlist" itemHeight="35" position="10,90" size="1180,665" enableWrapAround="1" scrollbarMode="showOnDemand" />
                <eLabel backgroundColor="grey" position="10,770" size="1180,1" />
                <ePixmap position="710,780" size="60,30" pixmap="/usr/lib/enigma2/python/Plugins/Extensions/Foreca/buttons/key_ok.png" />
                <widget source="key_ok" render="Label" position="790,780" size="250,35" font="Regular;30" />
                <ePixmap position="1120,780" size="60,30" pixmap="skin_default/icons/help.png" />
            </screen>"""
        elif size_w == 2560:
            self.skin = """
            <screen name="CityPanel" position="center,240" size="1240,1040" title="Select a city" >
                <ePixmap pixmap="skin_default/buttons/green.png" position="20,10" size="400,80" />
                <ePixmap pixmap="skin_default/buttons/yellow.png" position="420,10" size="400,80" />
                <ePixmap pixmap="skin_default/buttons/blue.png" position="820,10" size="400,80" />
                <widget source="key_green" render="Label" position="20,10" size="400,80" zPosition="1" font="Regular;40" halign="center" valign="center" backgroundColor="#1f771f" transparent="1" shadowColor="black" shadowOffset="-2,-2" />
                <widget source="key_yellow" render="Label" position="420,10" size="400,80" zPosition="1" font="Regular;40" halign="center" valign="center" backgroundColor="#a08500" transparent="1" shadowColor="black" shadowOffset="-2,-2" />
                <widget source="key_blue" render="Label" position="820,10" size="400,80" zPosition="1" font="Regular;40" halign="center" valign="center" backgroundColor="#18188b" transparent="1" shadowColor="black" shadowOffset="-2,-2" />
                <eLabel position="20,100" size="1200,2" backgroundColor="grey" />
                <widget name="Mlist" itemHeight="60" position="20,110" size="1200,840" enableWrapAround="1" scrollbarMode="showOnDemand" />
                <eLabel position="20,960" size="1200,2" backgroundColor="grey" />
                <widget source="key_ok" render="Label" position="860,980" size="280,50" font="Regular;44" />
                <ePixmap position="720,980" size="100,50" pixmap="/usr/lib/enigma2/python/Plugins/Extensions/Foreca/buttons/key_ok.png" />
                <ePixmap position="1120,980" size="100,50" pixmap="/usr/lib/enigma2/python/Plugins/Extensions/Foreca/buttons/key_help.png" />
            </screen>"""
        else:
            self.skin = """
            <screen name="CityPanel" position="center,120" size="620,520" title="Select a city" >
                <ePixmap pixmap="skin_default/buttons/green.png" position="10,5" size="200,40" />
                <ePixmap pixmap="skin_default/buttons/yellow.png" position="210,5" size="200,40" />
                <ePixmap pixmap="skin_default/buttons/blue.png" position="410,5" size="200,40" />
                <widget source="key_green" render="Label" position="10,5" size="200,40" zPosition="1" font="Regular;20" halign="center" valign="center" backgroundColor="#1f771f" transparent="1" shadowColor="black" shadowOffset="-2,-2" />
                <widget source="key_yellow" render="Label" position="210,5" size="200,40" zPosition="1" font="Regular;20" halign="center" valign="center" backgroundColor="#a08500" transparent="1" shadowColor="black" shadowOffset="-2,-2" />
                <widget source="key_blue" render="Label" position="410,5" size="200,40" zPosition="1" font="Regular;20" halign="center" valign="center" backgroundColor="#18188b" transparent="1" shadowColor="black" shadowOffset="-2,-2" />
                <eLabel position="10,50" size="600,1" backgroundColor="grey" />
                <widget name="Mlist" itemHeight="30" position="10,55" size="600,420" enableWrapAround="1" scrollbarMode="showOnDemand" />
                <eLabel position="10,480" size="600,1" backgroundColor="grey" />
                <widget source="key_ok" render="Label" position="430,490" size="140,25" font="Regular;22" />
                <ePixmap position="370,490" size="50,25" pixmap="/usr/lib/enigma2/python/Plugins/Extensions/Foreca/buttons/key_ok.png" />
                <ePixmap position="560,490" size="50,25" pixmap="/usr/lib/enigma2/python/Plugins/Extensions/Foreca/buttons/key_help.png" />
            </screen>"""

        Screen.__init__(self, session)
        self.setup_title = _("Select a city")
        self.Mlist = []
        self["Mlist"] = CityPanelList([])

        self.onChangedEntry = []

        self["key_green"] = StaticText(_("Favorite 1"))
        self["key_yellow"] = StaticText(_("Favorite 2"))
        self["key_blue"] = StaticText(_("Home"))
        self["key_ok"] = StaticText(_("Forecast"))
        self["Title"] = StaticText(_("Select a city"))

        HelpableScreen.__init__(self)
        self["actions"] = HelpableActionMap(self, "ForecaActions",
            {
                "cancel": (self.exit, _("Exit - End")),
                "left": (self.left, _("Left - Previous page")),
                "right": (self.right, _("Right - Next page")),
                "up": (self.up, _("Up - Previous")),
                "down": (self.down, _("Down - Next")),
                "ok": (self.ok, _("OK - Select")),
                "green": (self.green, _("Green - Assign to Favorite 1")),
                "yellow": (self.yellow, _("Yellow - Assign to Favorite 2")),
                "blue": (self.blue, _("Blue - Assign to Home")),
                "previous": (self.jump100_down, _("Previous - 100 back")),
                "next": (self.jump100_up, _("Next - 100 forward")),
                "9": (self.jump500_up, _("9 - 500 forward")),
                "7": (self.jump500_down, _("7 - 500 back"))
            }, -2)

        self.onShown.append(self.prepare)

    def prepare(self):
        self.maxidx = 0
        listIndex = 0
        if fileExists(USR_PATH + "/City.cfg"):
            file = open(USR_PATH + "/City.cfg", "r")
            for line in file:
                text = line.strip()
                if text == start_city:
                    listIndex = self.maxidx
                self.maxidx += 1
                self.Mlist.append(self.CityEntryItem((string.replace(text, "_", " "), text)))
            file.close
        self["Mlist"].l.setList(self.Mlist)
        #self["Mlist"].selectionEnabled(1)
        if listIndex:
            self["Mlist"].moveToIndex(listIndex)

    def jump500_up(self):
        cur = self["Mlist"].l.getCurrentSelectionIndex()
        if (cur + 500) <= self.maxidx:
            self["Mlist"].instance.moveSelectionTo(cur + 500)
        else:
            self["Mlist"].instance.moveSelectionTo(self.maxidx - 1)

    def jump500_down(self):
        cur = self["Mlist"].l.getCurrentSelectionIndex()
        if (cur - 500) >= 0:
            self["Mlist"].instance.moveSelectionTo(cur - 500)
        else:
            self["Mlist"].instance.moveSelectionTo(0)

    def jump100_up(self):
        cur = self["Mlist"].l.getCurrentSelectionIndex()
        if (cur + 100) <= self.maxidx:
            self["Mlist"].instance.moveSelectionTo(cur + 100)
        else:
            self["Mlist"].instance.moveSelectionTo(self.maxidx - 1)

    def jump100_down(self):
        cur = self["Mlist"].l.getCurrentSelectionIndex()
        if (cur - 100) >= 0:
            self["Mlist"].instance.moveSelectionTo(cur - 100)
        else:
            self["Mlist"].instance.moveSelectionTo(0)

    def up(self):
        self["Mlist"].up()
        self["Mlist"].selectionEnabled(1)

    def down(self):
        self["Mlist"].down()
        self["Mlist"].selectionEnabled(1)

    def left(self):
        self["Mlist"].pageUp()

    def right(self):
        self["Mlist"].pageDown()

    def exit(self):
        global menu
        menu = "stop"
        self.close()

    def ok(self):
        global city
        city = self['Mlist'].l.getCurrentSelection()[0][1]
        if DEBUG: print pluginPrintname, "city=", city, "CurrentSelection=", self['Mlist'].l.getCurrentSelection()
        self.close()

    def blue(self):
        global start, start_city
        city = sub(" ","_",self['Mlist'].l.getCurrentSelection()[0][1])
        if DEBUG: print pluginPrintname, "Home:", city
        fwrite = open(USR_PATH + "/startservice.cfg", "w")
        fwrite.write(city)
        fwrite.close()
        start_city = city
        start = city[city.rfind("/")+1:len(city)]
        message = "%s %s" % (_("This city is stored as home!\n\n                                  "), city)
        self.session.open( MessageBox, message, MessageBox.TYPE_INFO, timeout=8)

    def green(self):
        global fav1, fav1_city
        city = sub(" ","_",self['Mlist'].l.getCurrentSelection()[0][1])
        if DEBUG: print pluginPrintname, "Fav1:", city
        fwrite = open(USR_PATH + "/fav1.cfg", "w")
        fwrite.write(city)
        fwrite.close()
        fav1_city = city
        fav1 = city[city.rfind("/")+1:len(city)]
        message = "%s %s" % (_("This city is stored as favorite 1!\n\n                             "), city)
        self.session.open( MessageBox, message, MessageBox.TYPE_INFO, timeout=8)

    def yellow(self):
        global fav2, fav2_city
        city = sub(" ","_",self['Mlist'].l.getCurrentSelection()[0][1])
        if DEBUG: print pluginPrintname, "Fav2:", city
        fwrite = open(USR_PATH + "/fav2.cfg", "w")
        fwrite.write(city)
        fwrite.close()
        fav2_city = city
        fav2 = city[city.rfind("/") + 1:len(city)]
        message = "%s %s" % (_("This city is stored as favorite 2!\n\n                             "), city)
        self.session.open(MessageBox, message, MessageBox.TYPE_INFO, timeout=8)

    def CityEntryItem(self,entry):
        sizes = componentSizes[MainMenuList.SKIN_COMPONENT_KEY]
        textWidth = sizes.get(MainMenuList.SKIN_COMPONENT_TEXT_WIDTH, calcSkinFactor(600))
        textHeight = sizes.get(MainMenuList.SKIN_COMPONENT_TEXT_HEIGHT, calcSkinFactor(30))
        timeX = sizes.get(MainMenuList.SKIN_COMPONENT_TIME_X, calcSkinFactor(10))
        
        res = [entry]
        res.append(MultiContentEntryText(pos=(timeX, 0), size=(textWidth, textHeight), font=0, flags=RT_HALIGN_LEFT|RT_VALIGN_CENTER, text=entry[0], ))
        # res.append(MultiContentEntryText(pos=(col, 0), size=(1000, itemHeight), font=0, text=entry[0], color=weiss, color_sel=mblau, backcolor_sel=grau, flags=RT_VALIGN_CENTER))
        return res

#------------------------------------------------------------------------------------------
#------------------------------ Satellite photos ------------------------------------------
#------------------------------------------------------------------------------------------

class SatPanelList(MenuList):

    def __init__(self, list):
        MenuList.__init__(self, [], False, eListboxPythonMultiContent)
        tlf = TemplatedListFonts()
        self.l.setFont(0, gFont(tlf.face(tlf.BIGGER), tlf.size(tlf.BIGGER)))

# -----------------------------------------------------------------------------------------

class SatPanel(Screen, HelpableScreen):

    def __init__(self, session, ort):
        self.session = session
        self.ort = ort

        if size_w == 1920:
            self.skin = """
                <screen name="SatPanel" position="center,170" size="1200,820" title="Satellite photos" >
                    <ePixmap pixmap="skin_default/buttons/red.png" position="10,5" size="295,70" />
                    <ePixmap pixmap="skin_default/buttons/green.png" position="305,5" size="295,70" />
                    <ePixmap pixmap="skin_default/buttons/yellow.png" position="600,5" size="295,70" />
                    <ePixmap pixmap="skin_default/buttons/blue.png" position="895,5" size="295,70" />
                    <widget backgroundColor="#9f1313" font="Regular;30" halign="center" position="10,5" render="Label" shadowColor="black" shadowOffset="-2,-2" size="295,70" source="key_red" transparent="1" valign="center" zPosition="1" />
                    <widget backgroundColor="#1f771f" font="Regular;30" halign="center" position="305,5" render="Label" shadowColor="black" shadowOffset="-2,-2" size="295,70" source="key_green" transparent="1" valign="center" zPosition="1" />
                    <widget backgroundColor="#a08500" font="Regular;30" halign="center" position="600,5" render="Label" shadowColor="black" shadowOffset="-2,-2" size="295,70" source="key_yellow" transparent="1" valign="center" zPosition="1" />
                    <widget backgroundColor="#18188b" font="Regular;30" halign="center" position="895,5" render="Label" shadowColor="black" shadowOffset="-2,-2" size="295,70" source="key_blue" transparent="1" valign="center" zPosition="1" />
                    <eLabel backgroundColor="grey" position="10,80" size="1180,1" />
                    <widget enableWrapAround="1" name="Mlist" itemHeight="144" position="10,90" scrollbarMode="showOnDemand" size="1180,720" />
                </screen>"""
        elif size_w == 2560:
            self.skin = """
                <screen name="SatPanel" position="center,240" size="1640,1080" title="Satellite photos" >
                    <ePixmap pixmap="skin_default/buttons/red.png" position="20,10" size="400,80" />
                    <ePixmap pixmap="skin_default/buttons/green.png" position="420,10" size="400,80" />
                    <ePixmap pixmap="skin_default/buttons/yellow.png" position="820,10" size="400,80" />
                    <ePixmap pixmap="skin_default/buttons/blue.png" position="1220,10" size="400,80" />
                    <widget source="key_red" render="Label" position="20,10" size="400,80" zPosition="1" font="Regular;40" halign="center" valign="center" backgroundColor="#9f1313" transparent="1" shadowColor="black" shadowOffset="-2,-2" />
                    <widget source="key_green" render="Label" position="420,10" size="400,80" zPosition="1" font="Regular;40" halign="center" valign="center" backgroundColor="#1f771f" transparent="1" shadowColor="black" shadowOffset="-2,-2" />
                    <widget source="key_yellow" render="Label" position="820,10" size="400,80" zPosition="1" font="Regular;40" halign="center" valign="center" backgroundColor="#a08500" transparent="1" shadowColor="black" shadowOffset="-2,-2" />
                    <widget source="key_blue" render="Label" position="1220,10" size="400,80" zPosition="1" font="Regular;40" halign="center" valign="center" backgroundColor="#18188b" transparent="1" shadowColor="black" shadowOffset="-2,-2" />
                    <eLabel position="20,100" size="1600,2" backgroundColor="grey" />
                    <widget name="Mlist" itemHeight="320" position="20,110" size="1600,960" enableWrapAround="1" scrollbarMode="showOnDemand" />
                </screen>"""
        else:
            self.skin = """
                <screen name="SatPanel" position="center,120" size="820,540" title="Satellite photos" >
                    <ePixmap pixmap="skin_default/buttons/red.png" position="10,5" size="200,40" />
                    <ePixmap pixmap="skin_default/buttons/green.png" position="210,5" size="200,40" />
                    <ePixmap pixmap="skin_default/buttons/yellow.png" position="410,5" size="200,40" />
                    <ePixmap pixmap="skin_default/buttons/blue.png" position="610,5" size="200,40" />
                    <widget source="key_red" render="Label" position="10,5" size="200,40" zPosition="1" font="Regular;20" halign="center" valign="center" backgroundColor="#9f1313" transparent="1" shadowColor="black" shadowOffset="-2,-2" />
                    <widget source="key_green" render="Label" position="210,5" size="200,40" zPosition="1" font="Regular;20" halign="center" valign="center" backgroundColor="#1f771f" transparent="1" shadowColor="black" shadowOffset="-2,-2" />
                    <widget source="key_yellow" render="Label" position="410,5" size="200,40" zPosition="1" font="Regular;20" halign="center" valign="center" backgroundColor="#a08500" transparent="1" shadowColor="black" shadowOffset="-2,-2" />
                    <widget source="key_blue" render="Label" position="610,5" size="200,40" zPosition="1" font="Regular;20" halign="center" valign="center" backgroundColor="#18188b" transparent="1" shadowColor="black" shadowOffset="-2,-2" />
                    <eLabel position="10,50" size="800,1" backgroundColor="grey" />
                    <widget name="Mlist" itemHeight="160" position="10,55" size="800,480" enableWrapAround="1" scrollbarMode="showOnDemand" />
                </screen>"""

        Screen.__init__(self, session)
        self.setup_title = _("Satellite photos")
        self["Mlist"] = SatPanelList([])

        self.onChangedEntry = []

        self["key_red"] = StaticText(_("Continents"))
        self["key_green"] = StaticText(_("Europe"))
        self["key_yellow"] = StaticText(_("Germany"))
        self["key_blue"] = StaticText(_("Setup"))
        self["Title"] = StaticText(_("Satellite photos"))

        HelpableScreen.__init__(self)
        self["actions"] = HelpableActionMap(self, "ForecaActions",
            {
                "cancel": (self.exit, _("Exit - End")),
                "left": (self.left, _("Left - Previous page")),
                "right": (self.right, _("Right - Next page")),
                "up": (self.up, _("Up - Previous")),
                "down": (self.down, _("Down - Next")),
                "red": (self.MapsContinents, _("Red - Continents")),
                "green": (self.MapsEurope, _("Green - Europe")),
                "yellow": (self.MapsGermany, _("Yellow - Germany")),
                "blue": (self.PicSetupMenu, _("Blue - Settings")),
                "ok": (self.ok, _("OK - Show")),
            }, -2)
        self.onShown.append(self.prepare)

    def prepare(self):
        self.Mlist = []
        self.Mlist.append(self.SatEntryItem((_("Weather map Video"), 'sat')))
        self.Mlist.append(self.SatEntryItem((_("Showerradar Video"), 'rain')))
        self.Mlist.append(self.SatEntryItem((_("Temperature Video"), 'temp')))
        self.Mlist.append(self.SatEntryItem((_("Cloudcover Video"), 'cloud')))
        self.Mlist.append(self.SatEntryItem((_("Air pressure"), 'pressure')))
        self.Mlist.append(self.SatEntryItem((_("Eumetsat"), 'eumetsat')))

        self["Mlist"].l.setList(self.Mlist)
        self["Mlist"].selectionEnabled(1)

    def up(self):
        self["Mlist"].up()
        self["Mlist"].selectionEnabled(1)

    def down(self):
        self["Mlist"].down()
        self["Mlist"].selectionEnabled(1)

    def left(self):
        self["Mlist"].pageUp()

    def right(self):
        self["Mlist"].pageDown()

    def exit(self):
        global menu
        menu = "stop"
        self.close()

    def ok(self):
        menu = self['Mlist'].l.getCurrentSelection()[0][1]
        if DEBUG: print pluginPrintname, "SatPanel menu=", menu, "CurrentSelection=", self['Mlist'].l.getCurrentSelection()
        self.SatBild()

    def MapsGermany(self):
        itemList = [
            (_("Baden-Wuerttemberg"), 'badenwuerttemberg'),
            (_("Bavaria"), 'bayern'),
            (_("Berlin"), 'berlin'),
            (_("Brandenburg"), 'brandenburg'),
            (_("Bremen"), 'bremen'),
            (_("Hamburg"), 'hamburg'),
            (_("Hesse"), 'hessen'),
            (_("Mecklenburg-Vorpommern"), 'mecklenburgvorpommern'),
            (_("Lower Saxony"), 'niedersachsen'),
            (_("North Rhine-Westphalia"), 'nordrheinwestfalen'),
            (_("Rhineland-Palatine"), 'rheinlandpfalz'),
            (_("Saarland"), 'saarland'),
            (_("Saxony"), 'sachsen'),
            (_("Saxony-Anhalt"), 'sachsenanhalt'),
            (_("Schleswig-Holstein"), 'schleswigholstein'),
            (_("Thuringia"), 'thueringen'),
        ]
        itemList.sort(key=lambda i: locale.strxfrm(i[0]))
        self.Mlist = []
        for item in itemList:
            self.Mlist.append(self.SatEntryItem(item))
        self.session.open(SatPanelb, self.ort, _("Germany"), self.Mlist)

    def MapsEurope(self):
        itemList = [
            (_("Austria"), 'oesterreich'),
            (_("Belgium"), 'belgien'),
            (_("Czech Republic"), 'tschechien'),
            (_("Denmark"), 'daenemark'),
            (_("France"), 'frankreich'),
            (_("Germany"), 'deutschland'),
            (_("Greece"), 'griechenland'),
            (_("Great Britain"), 'grossbritannien'),
            (_("Hungary"), 'ungarn'),
            (_("Ireland"), 'irland'),
            (_("Italy"), 'italien'),
            (_("Latvia"), 'lettland'),
            (_("Luxembourg"), 'luxemburg'),
            (_("Netherlands"), 'niederlande'),
            (_("Poland"), 'polen'),
            (_("Portugal"), 'portugal'),
            (_("Russia"), 'russland'),
            (_("Slovakia"), 'slowakei'),
            (_("Spain"), 'spanien'),
            (_("Switzerland"), 'schweiz'),
        ]
        itemList.sort(key=lambda i: locale.strxfrm(i[0]))
        self.Mlist = []
        for item in itemList:
            self.Mlist.append(self.SatEntryItem(item))
        self.session.open(SatPanelb, self.ort, _("Europe"), self.Mlist)

    def MapsContinents(self):
        self.Mlist = []
        self.Mlist.append(self.SatEntryItem((_("Europe"), 'europa')))
        self.Mlist.append(self.SatEntryItem((_("North Africa"), 'afrika_nord')))
        self.Mlist.append(self.SatEntryItem((_("South Africa"), 'afrika_sued')))
        self.Mlist.append(self.SatEntryItem((_("North America"), 'nordamerika')))
        self.Mlist.append(self.SatEntryItem((_("Middle America"), 'mittelamerika')))
        self.Mlist.append(self.SatEntryItem((_("South America"), 'suedamerika')))
        self.Mlist.append(self.SatEntryItem((_("Middle East"), 'naherosten')))
        self.Mlist.append(self.SatEntryItem((_("East Asia"), 'ostasien')))
        self.Mlist.append(self.SatEntryItem((_("Southeast Asia"), 'suedostasien')))
        self.Mlist.append(self.SatEntryItem((_("Middle Asia"), 'zentralasien')))
        self.Mlist.append(self.SatEntryItem((_("Australia"), 'australienundozeanien')))
        self.session.open(SatPanelb, self.ort, _("Continents"), self.Mlist)

#------------------------------------------------------------------------------------------

    def SatEntryItem(self,entry):
        sizes = componentSizes[MainMenuList.SKIN_COMPONENT_KEY]
        text2Width = sizes.get(MainMenuList.SKIN_COMPONENT_TEXT2_WIDTH, calcSkinFactor(460))
        text2X = sizes.get(MainMenuList.SKIN_COMPONENT_TEXT2_X, calcSkinFactor(220))
        text2Height = sizes.get(MainMenuList.SKIN_COMPONENT_TEXT2_HEIGHT, calcSkinFactor(160))
        icon3Width = sizes.get(MainMenuList.SKIN_COMPONENT_ICON3_WIDTH, calcSkinFactor(200))
        icon3Height = sizes.get(MainMenuList.SKIN_COMPONENT_ICON3_HEIGHT, calcSkinFactor(140))
        
        res = [entry]
        #if DEBUG: print(pluginPrintname, "entry=", entry)
        thumb = LoadPixmap(THUMB_PATH + entry[1] + ".png")
        res.append(MultiContentEntryPixmapAlphaTest(pos=(0,10), size=(icon3Width,icon3Height), png=thumb))  # png vorn

        res.append(MultiContentEntryText(pos=(text2X , 0), size=(text2Width,text2Height), font=0, flags=RT_HALIGN_LEFT|RT_VALIGN_CENTER, text=entry[0], ))
        return res

    def PicSetupMenu(self):
        self.session.open(PicSetup)

#------------------------------------------------------------------------------------------

    def fetch_url(self, x):
        menu = self['Mlist'].l.getCurrentSelection()[0][1]
        url = ('https:%s' % x).replace('[TYPE]', menu)
        foundPos = url.find("0000.jpg")
        if DEBUG:
            print(pluginPrintname, "x=", x, "url=", url, "foundPos=", foundPos)
        if foundPos == -1:
            foundPos = url.find(".jpg")
        if foundPos == -1:
            foundPos = url.find(".png")
        file = url[foundPos - 10:foundPos]
        file2 = file[0:4] + "-" + file[4:6] + "-" + file[6:8] + " - " + file[8:10] + " " + _("h")
        if DEBUG:
            print(pluginPrintname, "file=", file, "file2=", file2)
        req = Request(url, headers=HEADERS)
        resp = urlopen(req, timeout=2)
        with open(CACHE_PATH + file2 + ".jpg", 'wb') as f:
            f.write(resp.read())

    def SatBild(self):
        menu = self['Mlist'].l.getCurrentSelection()[0][1]
        if DEBUG: print pluginPrintname, "SatBild menu=", menu, "CurrentSelection=", self['Mlist'].l.getCurrentSelection()

        if menu == "eumetsat":
            devicepath = "/tmp/meteogram.png"
            url = "http://www.sat24.com/images.php?country=eu&type=zoom&format=640x480001001&rnd=118538"
            req = Request(url, headers=HEADERS)
            resp = urlopen(req, timeout=2)
            with open(devicepath, 'wb') as f:
                f.write(resp.read())

            self.session.open(PicView, devicepath, 0, False)

        else:
            # https://www.foreca.it/Austria/Linz?map=sat
            devicepath = "/tmp/sat.html"
            url = "https://www.foreca.it" + "/" + pathname2url(self.ort) + "?map=" + menu
            # Load site for category and search Picture link
            fulltext = re.compile(r"'(\/\/cache-.+?)\'", re.DOTALL)
            req = Request(url, headers=HEADERS)
            resp = urlopen(req, timeout=2)

            # Load Picture for Slideshow
            urls = fulltext.findall(resp.read().decode('utf-8') if PY3 else resp.read())
            threads = [threading.Thread(target=self.fetch_url, args=(url,)) for url in urls]
            for thread in threads:
                thread.start()
            for thread in threads:
                thread.join()

            self.session.open(View_Slideshow, 0, True)

#------------------------------------------------------------------------------------------
#------------------------------ Weather Maps ----------------------------------------------
#------------------------------------------------------------------------------------------

class SatPanelListb(MenuList):

    def __init__(self, list):
        MenuList.__init__(self, [], False, eListboxPythonMultiContent)
        tlf = TemplatedListFonts()
        self.l.setFont(0, gFont(tlf.face(tlf.BIGGER), tlf.size(tlf.BIGGER)))

# -------------------------------------------------------------------

class SatPanelb(Screen, HelpableScreen):

    def __init__(self, session, ort, title, mlist):
        self.session = session
        self.ort = ort

        if size_w == 1920:
            self.skin = """
                <screen name="SatPanelb" position="center,170" size="1200,820" >
                    <widget enableWrapAround="1" name="Mlist" itemHeight="144" position="10,20" scrollbarMode="showOnDemand" size="1180,720" />
                    <eLabel backgroundColor="grey" position="10,760" size="1180,1" />
                    <ePixmap position="1030,780" size="60,30" pixmap="/usr/lib/enigma2/python/Plugins/Extensions/Foreca/buttons/key_ok.png" />
                    <ePixmap position="1120,780" size="60,30" pixmap="skin_default/icons/help.png" />
                </screen>"""
        elif size_w == 2560:
            self.skin = """
                 <screen name="SatPanelb" position="center,240" size="1640,1040" >
                    <widget name="Mlist" itemHeight="320" position="20,40" size="1600,960" enableWrapAround="1" scrollbarMode="showOnDemand" />
                </screen>"""
        else:
            self.skin = """
                <screen name="SatPanelb" position="center,120" size="820,520" >
                    <widget name="Mlist" itemHeight="160" position="10,20" size="800,480" enableWrapAround="1" scrollbarMode="showOnDemand" />
                </screen>"""

        Screen.__init__(self, session)
        self.setup_title = title
        self.Mlist = mlist
        #if DEBUG: print(pluginPrintname, "Mlist=", self.Mlist, "\nSatPanelListb([])=", SatPanelListb([]))
        self.onChangedEntry = []
        self["Mlist"] = SatPanelListb([])
        self["Mlist"].l.setList(self.Mlist)
        self["Mlist"].selectionEnabled(1)
        self["key_blue"] = StaticText(_("Settings"))
        self["Title"] = StaticText(title)

        HelpableScreen.__init__(self)
        self["actions"] = HelpableActionMap(self, "ForecaActions",
            {
                "cancel": (self.Exit, _("Exit - End")),
                "left": (self.left, _("Left - Previous page")),
                "right": (self.right, _("Right - Next page")),
                "up": (self.up, _("Up - Previous")),
                "down": (self.down, _("Down - Next")),
                "blue": (self.PicSetupMenu, _("Blue - Settings")),
                "ok": (self.ok, _("OK - Show")),
            }, -2)

    def up(self):
        self["Mlist"].up()
        self["Mlist"].selectionEnabled(1)

    def down(self):
        self["Mlist"].down()
        self["Mlist"].selectionEnabled(1)

    def left(self):
        self["Mlist"].pageUp()

    def right(self):
        self["Mlist"].pageDown()

    def Exit(self):
        global menu
        menu = "stop"
        self.close()

    def ok(self):
        menu = self['Mlist'].l.getCurrentSelection()[0][1]

        if DEBUG: print pluginPrintname, "SatPanelb menu=", menu, "CurrentSelection=", self['Mlist'].l.getCurrentSelection()
        self.SatBild()

    def PicSetupMenu(self):
        self.session.open(PicSetup)

#------------------------------------------------------------------------------------------

    def SatBild(self):

        region = self['Mlist'].l.getCurrentSelection()[0][1]
        devicepath = "/tmp/meteogram.png"
        url = "http://img.wetterkontor.de/karten/" + region + "0.jpg"
        req = Request(url, headers=HEADERS)
        resp = urlopen(req, timeout=2)
        with open(devicepath, 'wb') as f:
            f.write(resp.read())
        self.session.open(PicView, devicepath, 0, False)

#------------------------------------------------------------------------------------------
#-------------------------- Picture viewer for large pictures -----------------------------
#------------------------------------------------------------------------------------------

class PicView(Screen):

    def __init__(self, session, filelist, index, startslide):
        self.session = session
        self.bgcolor = config.plugins.foreca.bgcolor.value
        space = config.plugins.foreca.framesize.value

        self.skindir = "/tmp"
        self.skin = "<screen position=\"0,0\" size=\"" + str(size_w) + "," + str(size_h) + "\" > \
            <eLabel position=\"0,0\" zPosition=\"0\" size=\""+ str(size_w) + "," + str(size_h) + "\" backgroundColor=\""+ self.bgcolor +"\" /> \
            <widget name=\"pic\" position=\"" + str(space) + "," + str(space) + "\" size=\"" + str(size_w-(space*2)) + "," + str(size_h-(space*2)) + "\" zPosition=\"1\" alphatest=\"on\" /> \
            </screen>"

        Screen.__init__(self, session)
        self["actions"] = ActionMap(["OkCancelActions", "MediaPlayerActions"],
            {
                "cancel": self.Exit,
                "stop": self.Exit,
            }, -1)

        self["pic"] = Pixmap()
        self.filelist = filelist
        self.old_index = 0
        self.lastindex = index
        self.currPic = []
        self.shownow = True
        self.dirlistcount = 0
        self.index = 0
        self.picload = ePicLoad()
        self.picload_conn = self.picload.PictureData.connect(self.finish_decode)

        self.onLayoutFinish.append(self.setPicloadConf)
        self.startslide = startslide

    def setPicloadConf(self):
        sc = getScale()
        self.picload.setPara([self["pic"].instance.size().width(), self["pic"].instance.size().height(), sc[0], sc[1], 0, int(config.plugins.foreca.resize.value), self.bgcolor])
        self.start_decode()

    def ShowPicture(self):
        if self.shownow and len(self.currPic):
            self.shownow = False
            self["pic"].instance.setPixmap(self.currPic[0])

    def finish_decode(self, picInfo=""):
        ptr = self.picload.getData()
        if ptr != None:
            self.currPic = []
            self.currPic.append(ptr)
            self.ShowPicture()

    def start_decode(self):
        self.picload.startDecode(self.filelist)

    def Exit(self):
        del self.picload
        self.close(self.lastindex + self.dirlistcount)

#------------------------------------------------------------------------------------------
#------------------------------ Slide Show ------------------------------------------------
#------------------------------------------------------------------------------------------

class View_Slideshow(Screen):

    def __init__(self, session, pindex, startslide):

        pindex = 0
        print pluginPrintname, "SlideShow is running..."
        self.textcolor = config.plugins.foreca.textcolor.value
        self.bgcolor = config.plugins.foreca.bgcolor.value
        space = config.plugins.foreca.framesize.value
        fontsize = config.plugins.foreca.fontsize.value

        self.skindir = "/tmp"
        self.skin = "<screen position=\"0,0\" size=\"" + str(size_w) + "," + str(size_h) + "\" flags=\"wfNoBorder\" > \
            <eLabel position=\"0,0\" zPosition=\"0\" size=\"" + str(size_w) + "," + str(size_h) + "\" backgroundColor=\"" + self.bgcolor + "\" /> \
            <widget name=\"pic\" position=\"" + str(space) + "," + str(space + 40) + "\" size=\"" + str(size_w - (space * 2)) + "," + str(size_h - (space * 2) - 40) + "\" zPosition=\"1\" alphatest=\"on\" /> \
            <widget name=\"point\" position=\"" + str(space + 5) + "," + str(space + 10) + "\" size=\"20,20\" zPosition=\"2\" pixmap=\"" + THUMB_PATH + "record.png\" alphatest=\"on\" /> \
            <widget name=\"play_icon\" position=\"" + str(space + 25) + "," + str(space + 10) + "\" size=\"20,20\" zPosition=\"2\" pixmap=\"" + THUMB_PATH + "ico_mp_play.png\"  alphatest=\"on\" /> \
            <widget name=\"file\" position=\"" + str(space + 45) + "," + str(space + 10) + "\" size=\"" + str(size_w - (space * 2) - 50) + "," + str(fontsize + 5) + "\" font=\"Regular;" + str(fontsize) + "\" halign=\"left\" foregroundColor=\"" + self.textcolor + "\" zPosition=\"2\" noWrap=\"1\" transparent=\"1\" /> \
            </screen>"
        Screen.__init__(self, session)

        self["actions"] = ActionMap(["OkCancelActions", "MediaPlayerActions"],
            {
                "cancel": self.Exit,
                "stop": self.Exit,
                "pause": self.PlayPause,
                "play": self.PlayPause,
                "previous": self.prevPic,
                "next": self.nextPic,
            }, -1)
        self["point"] = Pixmap()
        self["pic"] = Pixmap()
        self["play_icon"] = Pixmap()
        self["file"] = Label(_("Please wait, photo is being loaded ..."))
        self.old_index = 0
        self.picfilelist = []
        self.lastindex = pindex
        self.currPic = []
        self.shownow = True
        self.dirlistcount = 0

        self.filelist = FileList(CACHE_PATH, showDirectories=False, matchingPattern="^.*\.(jpg)", useServiceRef=False)

        for x in self.filelist.getFileList():
            if x[0][0]:
                if x[0][1] == False:
                    self.picfilelist.append(CACHE_PATH + x[0][0])
                else:
                    self.dirlistcount += 1

        self.maxentry = len(self.picfilelist) - 1
        self.pindex = pindex - self.dirlistcount
        if self.pindex < 0:
            self.pindex = 0
        self.picload = ePicLoad()
        if os.path.exists("/var/lib/dpkg/status"):
            self.picload_conn = self.picload.PictureData.connect(self.finish_decode)
        else:
            self.picload.PictureData.get().append(self.finish_decode)
        self.slideTimer = eTimer()
        if os.path.exists("/var/lib/dpkg/status"):
            self.slideTimer_conn = self.slideTimer.timeout.connect(self.slidePic)
        else:
            self.slideTimer.callback.append(self.slidePic)
        if self.maxentry >= 0:
            self.onLayoutFinish.append(self.setPicloadConf)
        if startslide == True:
            self.PlayPause();

    def setPicloadConf(self):
        sc = getScale()
        self.picload.setPara([self["pic"].instance.size().width(), self["pic"].instance.size().height(), sc[0], sc[1], 0, int(config.plugins.foreca.resize.value), self.bgcolor])
        self["play_icon"].hide()
        if config.plugins.foreca.infoline.value == False:
            self["file"].hide()
        self.start_decode()

    def ShowPicture(self):
        if self.shownow and len(self.currPic):
            self.shownow = False
            self["file"].setText(self.currPic[0].replace(".jpg", ""))
            self.lastindex = self.currPic[1]
            self["pic"].instance.setPixmap(self.currPic[2])
            self.currPic = []
            self.next()
            self.start_decode()

    def finish_decode(self, picInfo=""):
        self["point"].hide()
        ptr = self.picload.getData()
        if ptr != None:
            text = ""
            try:
                text = picInfo.split('\n', 1)
                text = "(" + str(self.pindex + 1) + "/" + str(self.maxentry + 1) + ") " + text[0].split('/')[-1]
            except:
                pass
            self.currPic = []
            self.currPic.append(text)
            self.currPic.append(self.pindex)
            self.currPic.append(ptr)
            self.ShowPicture()

    def start_decode(self):
        self.picload.startDecode(self.picfilelist[self.pindex])
        self["point"].show()

    def next(self):
        self.pindex += 1
        if self.pindex > self.maxentry:
            self.pindex = 0

    def prev(self):
        self.pindex -= 1
        if self.pindex < 0:
            self.pindex = self.maxentry

    def slidePic(self):
        if DEBUG: print pluginPrintname, "slide to next Picture index=" + str(self.lastindex)
        if config.plugins.foreca.loop.value == False and self.lastindex == self.maxentry:
            self.PlayPause()
        self.shownow = True
        self.ShowPicture()

    def PlayPause(self):
        if self.slideTimer.isActive():
            self.slideTimer.stop()
            self["play_icon"].hide()
        else:
            self.slideTimer.start(config.plugins.foreca.slidetime.value * 1000)
            self["play_icon"].show()
            self.nextPic()

    def prevPic(self):
        self.currPic = []
        self.pindex = self.lastindex
        self.prev()
        self.start_decode()
        self.shownow = True

    def nextPic(self):
        self.shownow = True
        self.ShowPicture()

    def Exit(self):
        del self.picload
        for file in self.picfilelist:
            try:
                if DEBUG: print pluginPrintname, "file=", file
                os.unlink(file)
            except:
                pass
        self.close(self.lastindex + self.dirlistcount)


#------------------------------------------------------------------------------------------
#-------------------------------- Foreca Settings -----------------------------------------
#------------------------------------------------------------------------------------------

class PicSetup(Screen):

    if size_w == 1920:
        skin = """
        <screen name="PicSetup" position="center,170" size="1200,820" title="Setup" >
            <ePixmap pixmap="skin_default/buttons/red.png" position="10,5" scale="stretch" size="350,70" />
            <ePixmap pixmap="skin_default/buttons/green.png" position="360,5" scale="stretch" size="350,70" />
            <widget backgroundColor="#9f1313" font="Regular;30" halign="center" position="10,5" render="Label" shadowColor="black" shadowOffset="-2,-2" size="350,70" source="key_red" transparent="1" valign="center" zPosition="1" />
            <widget backgroundColor="#1f771f" font="Regular;30" halign="center" position="360,5" render="Label" shadowColor="black" shadowOffset="-2,-2" size="350,70" source="key_green" transparent="1" valign="center" zPosition="1" />
            <widget backgroundColor="background" font="Regular;34" halign="right" position="1050,25" render="Label" shadowColor="black" shadowOffset="-2,-2" size="120,40" source="global.CurrentTime" transparent="1">
                <convert type="ClockToText">Default</convert>
            </widget>
            <widget backgroundColor="background" font="Regular;34" halign="right" position="640,25" render="Label" shadowColor="black" shadowOffset="-2,-2" size="400,40" source="global.CurrentTime" transparent="1">
                <convert type="ClockToText">Date</convert>
            </widget>
            <eLabel backgroundColor="grey" position="10,80" size="1180,1" />
            <widget enableWrapAround="1" name="Mlist" position="10,90" scrollbarMode="showOnDemand" size="1180,720" />
        </screen>"""
    elif size_w == 2560:
        skin = """
        <screen name="PicSetup" position="center,240" size="1640,1060" title="Setup" >
            <ePixmap pixmap="skin_default/buttons/red.png" position="20,10" size="400,80" />
            <ePixmap pixmap="skin_default/buttons/green.png" position="420,10" size="400,80" />
            <widget render="Label" source="key_red" position="20,10" size="400,80" zPosition="5" valign="center" halign="center" backgroundColor="#9f1313" font="Regular;42" transparent="1" foregroundColor="white" shadowColor="black" shadowOffset="-1,-1" />
            <widget render="Label" source="key_green" position="420,10" size="400,80" zPosition="5" valign="center" halign="center" backgroundColor="#1f771f" font="Regular;42" transparent="1" foregroundColor="white" shadowColor="black" shadowOffset="-1,-1" />
            <eLabel position="20,100" size="1600,2" backgroundColor="grey" />
            <widget name="Mlist" position="20,120" size="1600,920" enableWrapAround="1" scrollbarMode="showOnDemand" />
        </screen>"""
    else:
        skin = """
        <screen name="PicSetup" position="center,120" size="820,520" title="Setup" >
            <ePixmap pixmap="skin_default/buttons/red.png" position="10,5" size="200,40" />
            <ePixmap pixmap="skin_default/buttons/green.png" position="210,5" size="200,40" />
            <widget render="Label" source="key_red" position="10,5" size="200,40" zPosition="5" valign="center" halign="center" backgroundColor="#9f1313" font="Regular;21" transparent="1" foregroundColor="white" shadowColor="black" shadowOffset="-1,-1" />
            <widget render="Label" source="key_green" position="210,5" size="200,40" zPosition="5" valign="center" halign="center" backgroundColor="#1f771f" font="Regular;21" transparent="1" foregroundColor="white" shadowColor="black" shadowOffset="-1,-1" />
            <eLabel position="10,50" size="800,1" backgroundColor="grey" />
            <widget name="Mlist" position="10,60" size="800,450" enableWrapAround="1" scrollbarMode="showOnDemand" />
        </screen>"""


    print pluginPrintname, "Setup..."
    def __init__(self, session):
        self.skin = PicSetup.skin
        Screen.__init__(self, session)
        self.setup_title = _("Setup")
        self["key_red"] = StaticText(_("Cancel"))
        self["key_green"] = StaticText(_("Save"))
        self["Title"] = StaticText(_("Setup"))
        self["actions"] = NumberActionMap(["SetupActions", "ColorActions"],
            {
                "ok": self.save,
                "save": self.save,
                "green": self.save,
                "cancel": self.cancel,
                "red": self.cancel,
                "left": self.keyLeft,
                "right": self.keyRight,
                "0": self.keyNumber,
                "1": self.keyNumber,
                "2": self.keyNumber,
                "3": self.keyNumber,
                "4": self.keyNumber,
                "5": self.keyNumber,
                "6": self.keyNumber,
                "7": self.keyNumber,
                "8": self.keyNumber,
                "9": self.keyNumber
            }, -3)
        self.list = []
        self["Mlist"] = ConfigList(self.list)

        self.list.append(getConfigListEntry(_("Select units"), config.plugins.foreca.units))
        self.list.append(getConfigListEntry(_("Select time format"), config.plugins.foreca.time))
        self.list.append(getConfigListEntry(_("City names as labels in the Main screen"), config.plugins.foreca.citylabels))
        self.list.append(getConfigListEntry(_("Show Foreca in extensions menu"),config.plugins.foreca.extmenu))
        self.list.append(getConfigListEntry(_("Frame size in full view"), config.plugins.foreca.framesize))

        self.list.append(getConfigListEntry(_("Scaling Mode"), config.plugins.foreca.resize))
        self.list.append(getConfigListEntry(_("Backgroundcolor"), config.plugins.foreca.bgcolor))
        self.list.append(getConfigListEntry(_("Slide Time (seconds)"), config.plugins.foreca.slidetime))

        self.list.append(getConfigListEntry(_("Slide picture in loop"), config.plugins.foreca.loop))
        self.list.append(getConfigListEntry(_("Show infoline"), config.plugins.foreca.infoline))
        self.list.append(getConfigListEntry(_("Font size infoline"), config.plugins.foreca.fontsize))
        self.list.append(getConfigListEntry(_("Textcolor infoline"), config.plugins.foreca.textcolor))
        self.list.append(getConfigListEntry(_("Debug"), config.plugins.foreca.debug))

    def save(self):
        for x in self["Mlist"].list:
            x[1].save()
        config.plugins.foreca.save()
        global DEBUG
        DEBUG = config.plugins.foreca.debug.value
        if DEBUG: print pluginPrintname, "Debug enabled"
        else: print pluginPrintname, "Debug disabled"
        self.refreshPlugins()
        self.close()

    def cancel(self):
        for x in self["Mlist"].list:
            x[1].cancel()
        self.close(False, self.session)

    def keyLeft(self):
        self["Mlist"].handleKey(KEY_LEFT)

    def keyRight(self):
        self["Mlist"].handleKey(KEY_RIGHT)

    def keyNumber(self, number):
        self["Mlist"].handleKey(KEY_0 + number)

    def refreshPlugins(self):
        from Components.PluginComponent import plugins
        from Tools.Directories import SCOPE_PLUGINS, resolveFilename
        plugins.clearPluginList()
        plugins.readPluginList(resolveFilename(SCOPE_PLUGINS))


