def mainlist(params,url,category):
    """Lists the main categories of the channel

    """
    logger.debug("[tvshac.py] mainlist")


    # Categories List
    test = config.get_localized_string(30900)
    xbmctools.addnewfolder( CHANNELNAME , "ListaSeries" , "Series" , str(getStr(30901)) , "http://tvshack.bz/tv" , thumbnail="" , plot="" ) #    <string id="30901">Series TV (VO)</string>
    xbmctools.addnewfolder( CHANNELNAME , "ListaDetallada" , "Cine" , config.get_localized_string(30902) , "http://tvshack.bz/movies" , thumbnail="" , plot="" )
    xbmctools.addnewfolder( CHANNELNAME , "ListaDetallada" , "Documentales" , getStr(30903) , "http://tvshack.bz/documentaries" , thumbnail="" , plot="" )
#    xbmctools.addnewfolder( CHANNELNAME , "ListaSeries" , "Anime" , getStr(30904) , "http://tvshack.bz/anime" , thumbnail="" , plot="" )
#    xbmctools.addnewfolder( CHANNELNAME , "ListaSeries" , "Musica" , getStr(30905) , "http://tvshack.bz/music" , thumbnail="" , plot="" )
#La música y el anime han desaparecido tras el último traslado de la web.
    xbmctools.addnewfolder( CHANNELNAME , "Buscar" , "" , getStr(30906) , "http://tvshack.bz/search/" , thumbnail=SEARCH_THUMBNAIL , plot="" )

    FinalizaPlugin (pluginhandle,category)
def ListaEpisodios(params,url,category):
    """Lists the episodes in a show
    """
    logger.info("[tvshack.py] ListaEpisodios")
    
    if params.has_key("Serie"):
        serie = params.get("Serie")
        logger.info("[tvshack.py] ListaEpisodios: Serie = "+serie)
    else:
        serie = ""

    # Adds "Add all to Library" option
    if category != 'Musica':
        xbmctools.addnewvideo( CHANNELNAME , "addlist2Library" , category , "", getStr (30920) , url , "" , "" , serie) #"A�ADIR TODOS LOS EPISODIOS A LA BIBLIOTECA"

    listaEp = devuelveListaEpisodios (params,url,category)

    for ep in listaEp:
            xbmctools.addnewvideo( CHANNELNAME , "listaVideosEpisodio" , category , "" , ep['title'] , ep['url'] , ep['thumbnail'] , ep['plot'] , Serie=serie)

    FinalizaPlugin (pluginhandle,category)
def Buscar (params,url,category):
    '''Searches globally through tvshack and shows results list
    '''
    logger.info("[tvshack.py] Buscar")
    
    keyboard = xbmc.Keyboard()
    keyboard.doModal()
    if not (keyboard.isConfirmed()):
        return
    text = keyboard.getText()
    if len(text) < 3:
        return
  
    #Clean search text to avoid web errors
    text = string.capwords(text).replace(" ", "+")
    searchUrl = url+text
  
    # Get the search results
    data = ""
    try:
        furl = urllib.urlopen(searchUrl)
        newurl = furl.geturl()
        if newurl != searchUrl:
            # This means we got only one result and jumped directly to it.
            # We have to analyze the result page to figure out the category
            dlog ('[tvshack] buscar: single result: '+ newurl)
            if newurl.find('/tv/') == 18: #TV Serie
                data = '<li><a href="%s">Television - <strong>%s</strong></a><a href="%s"><span>0 episodes</span></a></li>' % (newurl,newurl[22:-1],newurl)
            elif newurl.find("/movies/") == 18: #Film
                data = '<li><a href="%s">Movies - <strong>%s</strong></a><a href="%s"><span>%s</span></a></li>' % (newurl,newurl[26:-8],newurl,newurl[-6:-2])
            elif newurl.find("/music/") == 18: #Singer
                data = '<li><a href="%s">Music - <strong>%s</strong></a><a href="%s"></a></li>' % (newurl,newurl[25:-1],newurl)
        else:
            # Multiple search results
            data = furl.read()
        furl.close()
    except:
        # Probably Internet connection problems or web changes. Nothing we can do :(
        pass
    if len(data) == 0:
        logger.error ("[tvshac.py] Buscar - No search results :"+text)
        error = xbmcgui.Dialog()
        error.ok('pelisalacarta - TVShack',getStr(30907) ) #"The search did not find anything"
        return

# Ej. TV Series: <li><a href="http://tvshack.bz/tv/The_Big_Bang_Theory/">Television - <strong>The Big Bang Theory</strong></a><a href="http://tvshack.bz/tv/The_Big_Bang_Theory/"><span>57 episodes</span></a></li>
# Ej. Movie:     <li><a href="http://tvshack.bz/movies/Bang_Bang_You_re_Dead__2002_/">Movies - <strong>Bang Bang You're Dead</strong></a><a href="http://tvshack.bz/movies/Bang_Bang_You_re_Dead__2002_/"><span>2002</span></a></li>
# Ej. Music:     <li><a href="http://tvshack.bz/music/Mr__Big/">Music - <strong>Mr. Big</strong></a><a href="http://tvshack.bz/music/Mr__Big/"></a></li>
    patronvideos = '''(?x)       #      VERBOSE option active
        <li><a\ href="           #      Trash
        (?P<url>[^"]+)">         # $0 = media url
        ([^\ ]+)\ -\             # $1 = media Category: TV, Movie or Music
        <strong>                 #      Trash
        ([^<]+)                  # $2 = Media Name
        </strong></a>            #      Trash
        (?:<a\ href=")           #      Trash
        (?P=url)">               # $0 = media url (again)
        (?:<span>)?              #      Trash
        ([0-9]+)?                # $3 = Number of episodes or Production Year
        (?:\ episodes)?          #      Trash
        (?:</span>)?</a></li>    #      Trash
        ''' 
    matches = re.findall(patronvideos,data)
            
    totalmatches = len(matches)
    if totalmatches == 0:
        logger.error ("[tvshac.py] Buscar - No matches found: "+text)
        error = xbmcgui.Dialog()
        error.ok('pelisalacarta - TVShack',getStr(30907)) #'No matches found'
        return

    for match in matches:
        if match[1]== 'Television':
            # Add to the directory listing
            if match[3] != '0':
                scrapedtitle = getStr(30908) % (match[2],match[3]) #'Serie - %s (%s episodios)'
            else:
                scrapedtitle = getStr(30909) + match[2] #'Serie - '
            xbmctools.addnewfolder( CHANNELNAME , "ListaEpisodios" , "Series" , scrapedtitle , match[0] , "" , "" , Serie=match[2] , totalItems=totalmatches)
        elif match[1] == 'Movies':
            scrapedtitle = getStr(30910) % (match[2],match[3]) #'Cine - %s (%s)'
            xbmctools.addnewfolder( CHANNELNAME , "listaVideosEpisodio" , "Cine" , scrapedtitle , match[0] , "" , "" , totalItems=totalmatches)
        else: #Music
            xbmctools.addnewfolder( CHANNELNAME , "ListaEpisodios" , "Musica" , getStr(30911)+match[2] , match[0] , "" , "" , totalItems=totalmatches) #"M�sica - "

    FinalizaPlugin (pluginhandle,category)
def ListaSeries(params,url,category):
    """Creates the list for TV Shows, Anime and Music categories and shows it for selection
    """
    logger.info("[tvshack.py] ListaSeries")

    # We use a loading dialog box to give progress feedback.
    pDialog = xbmcgui.DialogProgress()
    text1 = getStr(30912) %(category,) #'Leyendo %s...'
#    text1 = 'Leyendo %s...' %(category,) #'Leyendo %s...'
    pDialog.create('pelisalacarta - TVSack' , text1)
    pDialog.update(0, text1)

    # Get the web page
    data = scrapertools.cachePage(url)
#    logger.info("[tvshack.py] Data="+data)

    # We extract the data using regex (patr�n in Spanish)
    # Ex. TV Show: <li><a href="/tv/30_Rock/">30 Rock <font class="new-updated">Updated!</font><span style="margin-top:0px;">69 episodes</span></a></li> 
    # Ex. Anime:   <li><a href="http://tvshack.bz/anime/Avatar__The_Abridged_Series/">Avatar: The Abridged Series<span style="margin-top:0px;">5 episodes</span></a></li>
    # Ex. Music:   <li><a href="http://tvshack.bz/music/Michael_Jackson/">Michael Jackson<span style="margin-top:0px;">27 songs</span></a></li>
    patronvideos = '''(?x)                                  # VERBOSE
        <li\ class="listm"><a\ href="                       # Trash
        (?:http://tvshack\.bz)?([^"]+)"                     # $0 = URL Path (relative) Ej. "/tv/The_Wire/"
        [^>]+>                                              # Trash
        ([^<]+)                                             # $1 = Media Name Ex. Wire, The
        (?:\ <font\ class="new-new">(New)!</font>)?         # $2 = 'New' if it's new media.
        (?:\ <font\ class="new-updated">(Updated)!</font>)? # $3 = 'Updated'
        \ <span\ style="[^"]+">                                # Trash
        ([0-9]+)                                            # $4 = Number of episodes Ex. 59
        \ ((?:Episodes)|(?:Songs))                          # $5 = Episodes/Song flag
                                 ''' 
    matches = re.compile(patronvideos).findall(data)

    totalseries = len(matches)
    if totalseries == 0:
        pDialog.close()
        error = xbmcgui.Dialog()
        error.ok('pelisalacarta - TVShack', getStr(30913)) #'Nothing found'
        FinalizaPlugin_con_error(pluginhandle,category)
        return
    i = 0
    step = 100 / totalseries
    for match in matches:
        #Show
        scrapedserie = match[1].decode("utf-8").encode('iso-8859-1',"ignore")
        #Progress indicator update
        i = i + step
        pDialog.update(i, text1+scrapedserie)

        #Show URL
        scrapedurl = "http://tvshack.bz" + match[0]

        # We elaborate on the title that will be shown adding 
        #     * Number of episodes.
        #     * If it's a new show.
        #     * If it's been updated recently.
        if match[5]=='Episodes':
            tipo_singular = getStr (30914) #'episodio'
            tipo_plural = getStr (30915) #'episodios'
        else: #'songs'
            tipo_singular = getStr (30916) #'canci�n'
            tipo_plural = getStr (30917) #'canciones'
        if match[4]=='1': #I like when software doesn't say "1 episodes" ;)
            scrapedtitle =    "%s (1 %s)" % (scrapedserie,tipo_singular) # Ex. House (1 episode)
        else:
            scrapedtitle = "%s (%s %s)" % (scrapedserie, match[4], tipo_plural) # Ex. House (69 episodes)

        if match[2]: #New Show
            scrapedtitle = scrapedtitle + getStr(30918) #" (Nuevo)"
        if match[3]: #Nuevos episodios
            scrapedtitle = scrapedtitle + getStr(30919) #" (Nuevos contenidos)"


        # This web doesn't have information about the show in the selection list
        #  This information is in the details view
        #  It will be very time compsumming to get the info now 
        #  if you think that there are more thatn 2000 TV shows
        #  I'm programming it anyway and keeping it just in case in the
        #  future someone programs smalled sellections (maybe alphabetical)

#        scrapedthumbnail, scrapednote = LeeDatosSerie (scrapedurl) #Slow for +100 shows

        scrapedthumbnail = ""
        scrapednote = ""
        
        # Addit to the list
        xbmctools.addnewfolder( CHANNELNAME , "ListaEpisodios" , category , scrapedtitle , scrapedurl , scrapedthumbnail , scrapednote , Serie=scrapedserie , totalItems=totalseries)

    #End of list creation
    pDialog.update(100, text1)
    FinalizaPlugin (pluginhandle,category)
    pDialog.close()