###########################################################
#
# Apple Quicktime Trailers script using iTunes XML files
#   -- based on AQTbrowser by Darkie
#
# @author Mouton <mouton_x@abuserz.com>
# @date 2005-10-10
# @version 1.37
#
###########################################################
# Modded by Donno for MC360
# Also made it so it runs xmlplus from a zip
maintainer = 'Mouton <mouton_x@abuserz.com>'

from os import mkdir, path
#from xbmc import Player as xbmcPlayer
import xbmcgui
import xbmc

import QuickTimeBrowser_utils as qtb

try: from xbmcgui import Emulating
except: Emulating = False

########################################
## Change those if needed ##############

# Max. seconds to wait for a response when downloading files
HTTP_TIMEOUT = 10.0

# If you use something else that -1 here, this default will be used to skip the Select Video dialog
# 3=FullScreen, 2=Large, 1=Medium, 0=Small, -1=Show dialog
DEFAULT_SIZE = -1

## Change to True to show debug information on the script console (white button when you are in the Scripts window in XBMC)
DEBUG = False

# Number of times the script will try to download a URL before giving up
DOWNLOAD_ATTEMPTS = 5

# Where downloaded trailers will be saved (if selected)
# Default to Q:\Scripts\QuickTimeBrowser\Downloaded Trailers
DOWNLOAD_DIR = path.join("E:\\", 'QuickTimeBrowser', 'Downloaded Trailers')

# Fetch Opening this week, Exclusive & Newest trailers on each reload ? (True/False)
PARSE_ON_RESTART = False

# Define the background image to use, if any.
BACKGROUND = None
#BACKGROUND = 'background3.png'

HIDE_SOME_DIALOGS = 1  # set to 1 to hide some of the dialogs

## Config ends here ####################
########################################

# global progress dialog
#dialog.Progress = xbmcgui.DialogProgress()
loadedMovies = []
config = qtb.Config()
firstUpdate = True

#defines
STATE_MOVIES_LIST       = 1
STATE_STUDIOS           = 2
STATE_CATEGORIES        = 3
STATE_FAVORITES         = 4
STATE_STUDIOS_MOVIES    = 5
STATE_CATEGORIES_MOVIES = 6

ACTION_MOVE_LEFT      = 1
ACTION_MOVE_RIGHT     = 2
ACTION_MOVE_UP        = 3
ACTION_MOVE_DOWN      = 4
ACTION_PAGE_UP        = 5
ACTION_PAGE_DOWN      = 6
ACTION_SELECT_ITEM    = 7
ACTION_HIGHLIGHT_ITEM = 8
ACTION_PARENT_DIR     = 9
ACTION_PREVIOUS_MENU  = 10
ACTION_SHOW_INFO      = 11
ACTION_PAUSE          = 12
ACTION_STOP           = 13
ACTION_NEXT_ITEM      = 14
ACTION_PREV_ITEM      = 15

qtb.DEBUG = DEBUG
qtb.HTTP_TIMEOUT = HTTP_TIMEOUT
qtb.DOWNLOAD_ATTEMPTS = DOWNLOAD_ATTEMPTS
button_normal="button-nofocus.png"
button_hl="button-focus.png"
lcf="iconlist-nofocus.png"
lcnf="iconlist-focus.png"
fc = "0xFF000000"

TMP_DIR = path.join("Z:\\", 'QuickTimeBrowser', 'Temp')
print('TMP_DIR = '+TMP_DIR)
from shutil import rmtree
rmtree(TMP_DIR,True)
try:
    mkdir(TMP_DIR)
except:
    pass

print('DOWNLOAD_DIR = '+DOWNLOAD_DIR)
if not path.exists(DOWNLOAD_DIR):
    try:
        mkdir(DOWNLOAD_DIR)
    except Exception:
        pass

def printDebug(text,mode=0):
    qtb.printDebug(text,mode)
def SetupButtons(self,x,y,tw,h,a="Vert",f="button_focus.png",nf="button_nofocus.png",gap=0,txtOffSet=0,font='font13',tfc="0xFF000000"):
    self.numbut  = 0
    self.butx = x
    self.buty = y
    self.butwidth = tw
    self.butheight = h
    self.butalign = a
    self.butfocus_img = f
    self.butnofocus_img = nf
    self.gap = gap
    self.fc = tfc
    self.txtOffSet = txtOffSet
    self.font=font
def AddButton(self,text):
    if self.butalign == "Hori":
        c = xbmcgui.ControlButton(self.butx + (self.numbut * self.butwidth + self.gap * self.numbut),self.buty,self.butwidth,self.butheight,text,self.butfocus_img,self.butnofocus_img,textColor=self.fc)
        self.addControl(c)
    elif self.butalign == "Vert":
        c = xbmcgui.ControlButton(self.butx ,self.buty + (self.numbut * self.butheight + self.gap* self.numbut) ,self.butwidth,self.butheight,text,self.butfocus_img,self.butnofocus_img,textColor=self.fc)
        self.addControl(c)
    else:
        c = xbmcgui.ControlButton(self.butx ,self.buty + (self.numbut * self.butheight + self.gap* self.numbut) ,self.butwidth,self.butheight,text,self.butfocus_img,self.butnofocus_img,textColor=self.fc)
        self.addControl(c)
    self.numbut += 1
    return c
# dialog for selecting the video size
# small / medium / large / fullscreen
def VideoSize(trailers):
    mysize = []
    print trailers
    size = len(trailers)
    vsselect = -1
    for i in range(1,size+1):
        mysize.append(qtb.getTrailerName(trailers[i-1]))
    vsselect = xbmcgui.Dialog().select("Movie Trailers",mysize)
    return vsselect

class AQTBrowser(xbmcgui.Window):
    def __init__(self):
        if Emulating: xbmcgui.Window.__init__(self)

        self.scaleX = ( float(self.getWidth())  / float(720) )
        self.scaleY = ( float(self.getHeight()) / float(480) )
        self.stop = False
        self.currentState = None
        self.selectedDistributor = -1
        self.current_size = 0


        if BACKGROUND and not Emulating:
            self.addControl(xbmcgui.ControlImage(0,0, int(720*self.scaleX),int(480*self.scaleY), BACKGROUND))
        # MC360 NEW BLOCK
        self.addControl(xbmcgui.ControlImage(0,0, int(720*self.scaleX),int(480*self.scaleY), 'background-blue.png'))
        self.addControl(xbmcgui.ControlImage(18,0, int(720*self.scaleX),int(480*self.scaleY), xbmc.getInfoLabel('Skin.String(Media)'))) # Hoping this works
        self.addControl(xbmcgui.ControlImage(int(70*self.scaleX),0, int(16*self.scaleX),int(54*self.scaleY), 'bkgd-whitewash-glass-top-left.png'))
        self.addControl(xbmcgui.ControlImage(int(86*self.scaleX),0, int(667*self.scaleX),int(54*self.scaleY), 'bkgd-whitewash-glass-top-middle.png'))
        self.addControl(xbmcgui.ControlImage(int(753*self.scaleX),0, int(16*self.scaleX),int(54*self.scaleY), 'bkgd-whitewash-glass-top-right.png'))
        self.addControl(xbmcgui.ControlImage(int(86*self.scaleX),int(427*self.scaleY), int(667*self.scaleX),int(54*self.scaleY), 'bkgd-whitewash-glass-bottom-middle.png'))
        self.addControl(xbmcgui.ControlImage(int(70*self.scaleX),int(427*self.scaleY), int(16*self.scaleX),int(54*self.scaleY), 'bkgd-whitewash-glass-bottom-left.png'))
        self.addControl(xbmcgui.ControlImage(int(753*self.scaleX),int(427*self.scaleY), int(667*self.scaleX),int(54*self.scaleY), 'bkgd-whitewash-glass-bottom-right.png'))
        self.addControl(xbmcgui.ControlImage(int(60*self.scaleX),0, int(32*self.scaleX),int(480*self.scaleY), 'background-overlay-whitewash-left.png'))
        self.addControl(xbmcgui.ControlImage(int(92*self.scaleX),0, int(628*self.scaleX),int(480*self.scaleY), 'background-overlay-whitewash-centertile.png'))
        #self.addControl(xbmcgui.ControlImage(int(720*self.scaleX),int(64*self.scaleY), int(667*self.scaleX),int(54*self.scaleY), 'background-overlay-whitewash-right.png'))
        self.addControl(xbmcgui.ControlImage(int(-61*self.scaleX),0, int(128*self.scaleX),int(480*self.scaleY), 'blades-runner-left.png'))
        self.addControl(xbmcgui.ControlImage(int(18*self.scaleX),0, int(80*self.scaleX),int(480*self.scaleY), 'blades-size4-header.png'))
        self.addControl(xbmcgui.ControlLabel(int(102*self.scaleX),int(35*self.scaleY), int(200*self.scaleX),int(35*self.scaleY), 'Movie Trailers', font="font18"))

        self.addControl(xbmcgui.ControlImage(int(125*self.scaleX),int(420.833333*self.scaleY), int(21*self.scaleX),int(17.5*self.scaleY), 'button-Y.png'))

        self.x_desc =  xbmcgui.ControlLabel(int(145*self.scaleX),int(440*self.scaleY), int(200*self.scaleX),int(35*self.scaleY), '',font="font12")
        self.addControl(self.x_desc)
        if xbmc.Player().isPlayingAudio():
            self.x_desc.setLabel('Full Screen Visualization')
            self.x_img = xbmcgui.ControlImage(int(112*self.scaleX),int(437.5*self.scaleY), int(21*self.scaleX),int(17.5*self.scaleY), 'button-X.png')
            self.addControl(self.x_img)
        elif xbmc.Player().isPlayingVideo():
            self.x_img = xbmcgui.ControlImage(int(112*self.scaleX),int(437.5*self.scaleY), int(21*self.scaleX),int(17.5*self.scaleY), 'button-X.png')
            self.addControl(self.x_img)
            self.x_desc.setLabel('Full Screen Video')
        else:
            self.x_img = xbmcgui.ControlImage(int(112*self.scaleX),int(437.5*self.scaleY), int(21*self.scaleX),int(17.5*self.scaleY), 'button-X-turnedoff.png')
            self.addControl(self.x_img)
            self.x_desc.setLabel('')
        
        self.addControl(xbmcgui.ControlImage(int(633*self.scaleX),int(437.5*self.scaleY), int(21*self.scaleX),int(17.5*self.scaleY), 'button-A.png'))
        self.addControl(xbmcgui.ControlImage(int(620*self.scaleX),int(420.833333*self.scaleY), int(21*self.scaleX),int(17.5*self.scaleY), 'button-B.png'))
        self.addControl(xbmcgui.ControlLabel(int(623*self.scaleX),int(440*self.scaleY), int(200*self.scaleX),int(35*self.scaleY), 'Select',alignment=1,font="font12"))
        self.addControl(xbmcgui.ControlLabel(int(610*self.scaleX),int(423.333*self.scaleY), int(200*self.scaleX),int(35*self.scaleY), 'Back',alignment=1,font="font12"))
        self.addControl(xbmcgui.ControlLabel(int(155*self.scaleX),int(423.333*self.scaleY), int(200*self.scaleX),int(35*self.scaleY), 'Add to Favorites',font="font12"))
        
        self.addControl(xbmcgui.ControlLabel(int(79*self.scaleX),int(129.1666*self.scaleY), int(270*self.scaleX),int(35*self.scaleY), 'media',angle=270,textColor="0xFF000000",font="font14"))
        self.list = xbmcgui.ControlList(int(270*self.scaleX), int(70*self.scaleY), int(430*self.scaleX), int(340*self.scaleY),"font13",fc,lcf,lcnf,itemTextXOffset=-5)


        SetupButtons(self, int(90*self.scaleX), int(70*self.scaleY), int(170*self.scaleX), int(30*self.scaleY), "Vert", button_hl,button_normal, -2,30)
        #self.btnExclusive = AddButton(self,'Exclusive')
        self.btnOpening =  AddButton(self,'Opening Week')
        self.btnNewest = AddButton(self,'Newest')
        self.btnStudios =AddButton(self,'Studios')
        self.btnGenres =  AddButton(self,'Genres')
        self.btnAll =  AddButton(self,'Show All')

        self.btnNew = AddButton(self,'New Trailers')
        self.btnFavorites = AddButton(self,'Favorites')
        self.btnUpdate = AddButton(self,'Update')
        #self.btnUpdate2 = AddButton(self,'Update All')

        self.checkDownload = xbmcgui.ControlCheckMark(int(100*self.scaleX), int(365*self.scaleY), int(120*self.scaleX), int(20*self.scaleY), "Download", checkWidth=20, checkHeight=20, alignment=1,textColor=fc)
        self.checkSave     = xbmcgui.ControlCheckMark(int(100*self.scaleX), int(340*self.scaleY), int(120*self.scaleX), int(20*self.scaleY), "Save", checkWidth=20, checkHeight=20, alignment=1,textColor="0xFFFFFFFF")

        self.labelStatus = xbmcgui.ControlLabel(int(300*self.scaleX), int(439*self.scaleY), int(150*self.scaleX), int(20*self.scaleY), "Saving data files..." )

        self.addControl(self.list)

        self.addControl(self.checkDownload)
        self.addControl(self.checkSave)

        # Load config
        self.checkDownload.setSelected(config.download)
        self.checkSave.setSelected(config.save)

        self.list.controlLeft(self.btnOpening)
        """
        self.btnExclusive.controlUp(self.checkDownload)
        self.btnExclusive.controlDown(self.btnOpening)
        self.btnExclusive.controlRight(self.list)
        """
        self.btnOpening.controlUp(self.checkDownload)
        self.btnOpening.controlDown(self.btnNewest)
        self.btnOpening.controlRight(self.list)

        self.btnNewest.controlUp(self.btnOpening)
        self.btnNewest.controlDown(self.btnStudios)
        self.btnNewest.controlRight(self.list)

        self.btnStudios.controlUp(self.btnNewest)
        self.btnStudios.controlDown(self.btnGenres)
        self.btnStudios.controlRight(self.list)

        self.btnGenres.controlUp(self.btnStudios)
        self.btnGenres.controlDown(self.btnAll)
        self.btnGenres.controlRight(self.list)

        self.btnAll.controlUp(self.btnGenres)
        self.btnAll.controlDown(self.btnNew)
        self.btnAll.controlRight(self.list)
        self.btnNew.controlUp(self.btnAll)
        self.btnNew.controlDown(self.btnFavorites)
        self.btnNew.controlRight(self.list)

        self.btnFavorites.controlUp(self.btnNew)
        self.btnFavorites.controlDown(self.btnUpdate)
        self.btnFavorites.controlRight(self.list)

        self.btnUpdate.controlUp(self.btnFavorites)
        self.btnUpdate.controlDown(self.checkSave)
        self.btnUpdate.controlRight(self.list)

        self.checkDownload.controlUp(self.checkSave)
        self.checkDownload.controlDown(self.btnOpening)
        self.checkDownload.controlRight(self.list)
        self.checkSave.controlUp(self.btnUpdate)
        self.checkSave.controlDown(self.checkDownload)
        self.checkSave.controlRight(self.list)
        self.addControl(xbmcgui.ControlImage(60,78, int(200*self.scaleX),int(355*self.scaleY), "systemhomebutton-1-top.png"))
        xbmcgui.unlock()

    def onAction(self, action):
        global loadedMovies
        # Y on controller or 1 on remote adds or remove favorites
        if action == 34 or action == 59:
            if self.currentState == STATE_MOVIES_LIST or self.currentState == STATE_STUDIOS_MOVIES or self.currentState == STATE_CATEGORIES_MOVIES:
                if self.list.getSelectedPosition() != -1:
                    movie = loadedMovies[self.list.getSelectedPosition()]
                    config.favorites.append(movie)
                    config.dump()
                    xbmcgui.Dialog().ok('Favorites',movie.title, 'Added to Favorites.')
            elif self.currentState == STATE_FAVORITES:
                if self.list.getSelectedPosition() < 0 or len(loadedMovies) == 0:
                    return
                movie = loadedMovies[self.list.getSelectedPosition()]
                config.favorites.remove(movie)
                config.dump()
                xbmcgui.Dialog().ok('Favorites',movie.title ,'Removed from your Favorites.')
                loadedMovies = config.favorites
                self.list.reset()
                for movie in loadedMovies:
                    self.list.addItem(movie.title)
                xbmcgui.unlock()
        if action == ACTION_PREVIOUS_MENU:
            self.close()
        elif action == ACTION_PARENT_DIR:
            if self.currentState == STATE_STUDIOS_MOVIES:
                printDebug('Studios button pressed (back to parent).')
                self.currentState = STATE_STUDIOS
                studios = qtb.getAllStudios()
                self.list.reset()
                for studio in studios:
                    self.list.addItem(studio.name)
                xbmcgui.Unlock()
            if self.currentState == STATE_CATEGORIES_MOVIES:
                printDebug('Genres button pressed (back to parent).')
                self.currentState = STATE_CATEGORIES
                categories = qtb.getAllCategories()
                self.list.reset()
                for category in categories:
                    self.list.addItem(category.name)
                xbmcgui.Unlock()

    def onControl(self, control):
        global firstUpdate, loadedMovies
        loadMovies = False
        old_loadedMovies = loadedMovies
        if control == self.btnFavorites:
            printDebug('Favorites button pressed.')
            loadedMovies = config.favorites
            loadMovies = True
            if len(loadedMovies) > 0:
                self.list.controlLeft(self.btnFavorites)
                self.currentState = STATE_FAVORITES
        elif control == self.btnUpdate:
            printDebug('Update button pressed.')
            if xbmc.Player().isPlaying():
                qtb.parse(loaded=True,update_all=True)
                if xbmcgui.Dialog().yesno("Moive Trailers", "You are Playing Media","Continuing Will Stop Media","Continue?"):
                    xbmc.Player().stop()
                    qtb.parse(loaded=True,update_all=False)
            else:
                qtb.parse(loaded=True,update_all=False)

            """
            if firstUpdate:
                qtb.parse(loaded=True,update_all=False)
                firstUpdate = False
            else:
                firstUpdate = True
            """


            # Switch Update and Update All buttons -- Removed
            """
            self.removeControl(self.btnUpdate)
            tmp = self.btnUpdate
            self.btnUpdate = self.btnUpdate2
            self.btnUpdate2 = tmp
            self.addControl(self.btnUpdate)
            self.btnUpdate.controlUp(self.btnFavorites)
            self.btnUpdate.controlDown(self.checkDownload)
            self.btnUpdate.controlRight(self.list)
            self.btnFavorites.controlDown(self.btnUpdate)
            self.checkDownload.controlUp(self.btnUpdate)
            self.setFocus(self.btnUpdate)
            """

        elif control == self.checkSave:
            printDebug('Save checkbox pressed.')
            if self.checkSave.getSelected():
                self.checkDownload.setSelected(True)
            config.download = self.checkDownload.getSelected()
            config.save = self.checkSave.getSelected()
            config.dump()
        elif control == self.checkDownload:
            printDebug('Download checkbox pressed.')
            if not self.checkDownload.getSelected() and self.checkSave.getSelected():
                xbmcgui.Dialog().ok('Error','For trailers to be save','they need to be downloaded first.')
                self.checkDownload.setSelected(True)
            config.download = self.checkDownload.getSelected()
            config.save = self.checkSave.getSelected()
            config.dump()
            """
            elif control == self.btnExclusive:
                printDebug('Exclusive button pressed.')
                loadedMovies = qtb.exclusiveMovies
                loadMovies = True
                if len(loadedMovies) > 0:
                    self.list.controlLeft(self.btnExclusive)
                    self.currentState = STATE_MOVIES_LIST
            """
        elif control == self.btnOpening:
            printDebug('Opening This Week button pressed.')
            loadedMovies = qtb.openingMovies
            loadMovies = True
            if len(loadedMovies) > 0:
                self.list.controlLeft(self.btnOpening)
                self.currentState = STATE_MOVIES_LIST
        elif control == self.btnNewest:
            printDebug('Newest button pressed.')
            loadedMovies = qtb.newestMovies
            loadMovies = True
            if len(loadedMovies) > 0:
                self.list.controlLeft(self.btnNewest)
                self.currentState = STATE_MOVIES_LIST
        elif control == self.btnStudios:
            printDebug('Studios button pressed.')
            self.list.controlLeft(self.btnStudios)
            self.currentState = STATE_STUDIOS
            studios = qtb.getAllStudios()
            self.list.reset()
            for studio in studios:
                self.list.addItem(studio.name)
        elif control == self.btnGenres:
            printDebug('Genres button pressed.')
            self.list.controlLeft(self.btnGenres)
            self.currentState = STATE_CATEGORIES
            categories = qtb.getAllCategories()
            self.list.reset()
            for category in categories:
                self.list.addItem(category.name)
        elif control == self.btnAll:
            printDebug('All button pressed.')
            loadedMovies = qtb.getAllMovies(None,True)
            loadMovies = True
            if len(loadedMovies) > 0:
                self.list.controlLeft(self.btnAll)
                self.currentState = STATE_MOVIES_LIST
        elif control == self.btnNew:
            printDebug('New Trailers button pressed.')
            loadedMovies = qtb.newMovies
            loadMovies = True
            if len(loadedMovies) > 0:
                self.list.controlLeft(self.btnNew)
                self.currentState = STATE_MOVIES_LIST
        elif control == self.list:
            if self.currentState == STATE_STUDIOS:
                # We selected a Studio, show all movies produced by it
                if self.list.getSelectedPosition() < 0: return
                studios = qtb.getAllStudios()
                printDebug('Studio selected from list: ' + studios[self.list.getSelectedPosition()].name)
                loadedMovies = qtb.getAllMoviesFromStudio(studios[self.list.getSelectedPosition()])
                loadMovies = True
                if len(loadedMovies) > 0:
                    self.currentState = STATE_STUDIOS_MOVIES
            elif self.currentState == STATE_CATEGORIES:
                # We selected a Category, show all movies of this genre
                if self.list.getSelectedPosition() < 0: return
                categories = qtb.getAllCategories()
                printDebug('Category selected from list: ' + categories[self.list.getSelectedPosition()].name)
                loadedMovies = qtb.getAllMoviesFromCategory(categories[self.list.getSelectedPosition()])
                loadMovies = True
                if len(loadedMovies) > 0:
                    self.currentState = STATE_CATEGORIES_MOVIES
            elif self.currentState == STATE_MOVIES_LIST or self.currentState == STATE_STUDIOS_MOVIES or self.currentState == STATE_CATEGORIES_MOVIES or self.currentState == STATE_FAVORITES:
                if self.list.getSelectedPosition() < 0: return
                printDebug('Number of loaded movies = ' + str(len(loadedMovies)) + ', selected item = ' + str(self.list.getSelectedPosition()))
                
                self.Play(loadedMovies[self.list.getSelectedPosition()])

        if loadMovies:
            if len(loadedMovies) > 0:
                self.list.reset()
                for movie in loadedMovies:
                    self.list.addItem(movie.title)
            else:
                loadedMovies = old_loadedMovies
                if not HIDE_SOME_DIALOGS:
                    xbmcgui.Dialog().ok('Error','There are no trailers available', ' for this category.')

    def Parse(self):
        loaded = qtb.loadDataFiles(ResetTypes=False)
        if PARSE_ON_RESTART:
            result = qtb.parse(loaded)
        else:
            if loaded:
                qtb.loadMovieVars()
            result = 0
        if len(qtb.newMovies) > 0:
            self.setFocus(self.btnNew)
            self.onControl(self.btnNew)
        else:
            self.setFocus(self.btnOpening)
            self.onControl(self.btnOpening)
        return result

    def Play(self, movie):
        if movie is None:
            printDebug('cannot play None object.')
            return None
        printDebug('Playing movie: ' + movie.title.encode('ascii','replace'))
        dp = xbmcgui.DialogProgress()
        dp.create("Please wait...","Loading available trailers for this movie.")
        movie.loadMovieTrailersUrls()
        dp.close()
        if len(movie.trailers) == 0:
            printDebug('No Trailer has been found for this movie using the URL : ' + movie.xmlUrl)
            xbmcgui.Dialog().ok('Error!','No Trailer has been found for this movie using the URL :\n' + movie.xmlUrl)
            return

        if DEFAULT_SIZE == -1 or movie.hasCustomTrailer:
            sel = VideoSize(movie.trailers)
        else:
            sel = DEFAULT_SIZE

        if sel >= len(movie.trailers):
            sel = len(movie.trailers) - 1

        if sel != -1:
            link = movie.getMov(sel)

            if link is None or link == '':
                xbmcgui.Dialog().ok('Error!','No Trailer has been found for this movie using the URL:\n' + movie.trailers[sel])
            else:
                filename_download = get_filename_from_link(DOWNLOAD_DIR,link)
                filename_tmp = get_filename_from_link(TMP_DIR,link)
                if qtb.FileExists(filename_download):
                    link = filename_download
                elif qtb.FileExists(filename_tmp):
                    link = filename_tmp
                else:
                    if self.checkDownload.getSelected():

                        dp.create("Please wait...","Downloading file...")
                        printDebug('Downloading file: ' + link)
                        total_size = qtb.url_size(link)
                        stream = qtb.download_file(link,True)
                        movie_file = open(filename_tmp, 'wb')
                        printDebug('Reading downloaded file.')
                        chunk_size = 16*1024
                        self.current_size = 0
                        dp.update(0)

                        self.stop = False
                        from threading import Thread
                        speedSubThread = Thread(target=self.speed_meter, args=())
                        speedSubThread.start()
                        while 1:
                            chunk = stream.read(chunk_size)
                            if len(chunk) == 0: break
                            movie_file.write(chunk)
                            self.current_size = self.current_size + len(chunk)
                            dp.update(int(self.current_size*100/total_size))
                        self.stop = True
                        movie_file.close()

                        link = filename_tmp
                        self.removeControl(self.labelStatus)
                        dp.close()
                        if self.checkSave.getSelected():
                            dp2 = xbmcgui.DialogProgress()
                            dp2.create("Please wait...","Saving file...")
                            printDebug('Saving file to: ' + filename_download)
                            from shutil import move
                            move(filename_tmp,filename_download)
                            link = filename_download
                            dp2.close()

                try:
                    printDebug('Playing: ' + link)
                    #player = customPlayer()
                    player = xbmc.Player()
                    player.play(link)
                    self.removeControl(self.x_img)
                    self.x_img = xbmcgui.ControlImage(int(112*self.scaleX),int(437.5*self.scaleY), int(21*self.scaleX),int(17.5*self.scaleY), 'button-X.png')
                    self.addControl(self.x_img)
                    self.x_desc.setLabel('Full Screen Video')
                    

                except Exception,e:
                    print('Error caught in xbmc.Player().play('+link+')')
                    print('Error: ' + str(e))

    def speed_meter(self):
        from time import sleep
        addSpeedCheckpoint(0)
        if not Emulating:
            self.labelStatus.setLabel('Current speed: 0 kB/s')
            self.addControl(self.labelStatus)
        while not self.stop:
            sleep(1.000)
            addSpeedCheckpoint(self.current_size)
            speed = getCurrentSpeed()
            if Emulating:
                print('Current speed: ' + speed + ' kB/s')
            else:
                self.labelStatus.setLabel('Current speed: ' + speed + ' kB/s')

def addSpeedCheckpoint(size_value):
    from time import time
    time_value = time()
    global speed_values
    if (size_value == 0):
        speed_values = {}
    while len(speed_values) >= 5:
        min_key = 9999999999
        for key,value in speed_values.iteritems():
            if key < min_key:
                min_key = key
        del speed_values[min_key]
    speed_values[time_value] = size_value

def get_filename_from_link(directory,link):
    from string import rfind
    if rfind(link,'/') != -1:
        filename = path.join(directory, link[rfind(link,'/')+1:])
    else:
        filename = path.join(directory, link[rfind(link,'%2F')+3:])
    return filename

def getCurrentSpeed():
    min_key = 9999999999
    max_key = 0
    global speed_values
    for key,value in speed_values.iteritems():
        if key < min_key:
            min_key = key
        if key > max_key:
            max_key = key

    start_time = min_key
    start_size = speed_values[min_key]
    end_time = max_key
    end_size = speed_values[max_key]

    size = end_size - start_size
    time = end_time - start_time
    if time == 0: return '0'
    speed = float(size/1024/time)
    return "%.0f" % speed
"""
class customPlayer(xbmcPlayer):
    def __init__(self,w):
        self.win  = w
        return

    def onPlayBackStarted(self):
        from time import sleep
        printDebug('Playback started.')
        while self.isPlayingVideo():
            sleep(1.000)
        self.onPlayBackEnded()

    def onPlayBackStopped(self):
        self.onPlayBackEnded()

    def onPlayBackEnded(self):
        printDebug('Playback ended.')
"""
config.load()
w = AQTBrowser()
if w.Parse() != -1:
    w.doModal()
    rmtree(TMP_DIR,True)
    config.dump()
    # Save data files
    from threading import Thread
    checkSubThread = Thread(target=qtb.saveDataFiles, args=(False,True))
    checkSubThread.start()
del w
xbmc.executebuiltin('XBMC.ReplaceWindow(0)')

