# -*- coding: utf-8 -*-
import urllib2, urllib, xbmcgui, xbmcplugin, xbmc, re, sys, os,base64, random
import xbmcaddon
from addon.common.addon import Addon
import requests
from metahandler import metahandlers
import urlresolver
import dandyscrapers
s = requests.session() 

# A thanks to the great Mikey1234 for some the original code edited

User_Agent = 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.89 Safari/537.36'
addon_id='plugin.video.myriad_gw'
selfAddon = xbmcaddon.Addon(id=addon_id)
datapath= xbmc.translatePath(selfAddon.getAddonInfo('profile'))
addon = Addon(addon_id, sys.argv)
addon_name = selfAddon.getAddonInfo('name')
ART = xbmc.translatePath(os.path.join('special://home/addons/' + addon_id + '/resources/icons/'))
ICON = xbmc.translatePath(os.path.join('special://home/addons/' + addon_id, 'icon.png'))
FANART = xbmc.translatePath(os.path.join('special://home/addons/' + addon_id , 'fanart.jpg'))
metaset = selfAddon.getSetting('enable_meta')
metaget = metahandlers.MetaData()
getmov25 = selfAddon.getSetting('enable_mov25')
Dialog = xbmcgui.Dialog()
dp =  xbmcgui.DialogProgress()
BASEURL = 'http://akas.imdb.com'
BASEURL2 = 'http://www.imdb.com'
poolprox = ['http://buka.link', 'http://proxite.net','http://unblockthatsite.net']
PROXY =(random.choice(poolprox))

m_list_name1 = selfAddon.getSetting('movielist_name1')
m_list_id1 = selfAddon.getSetting('movielist_id1')

m_list_name2 = selfAddon.getSetting('movielist_name2')
m_list_id2 = selfAddon.getSetting('movielist_id2')

m_list_name3 = selfAddon.getSetting('movielist_name3')
m_list_id3 = selfAddon.getSetting('movielist_id3')

m_list_name4 = selfAddon.getSetting('movielist_name4')
m_list_id4 = selfAddon.getSetting('movielist_id4')

m_list_name5 = selfAddon.getSetting('movielist_name5')
m_list_id5 = selfAddon.getSetting('movielist_id5')

m_list_name6 = selfAddon.getSetting('movielist_name6')
m_list_id6 = selfAddon.getSetting('movielist_id6')

m_list_name7 = selfAddon.getSetting('movielist_name7')
m_list_id7 = selfAddon.getSetting('movielist_id7')

m_list_name8 = selfAddon.getSetting('movielist_name8')
m_list_id8 = selfAddon.getSetting('movielist_id8')

m_list_name9 = selfAddon.getSetting('movielist_name9')
m_list_id9 = selfAddon.getSetting('movielist_id9')

m_list_name10 = selfAddon.getSetting('movielist_name10')
m_list_id10 = selfAddon.getSetting('movielist_id10')

Hosts = []
hd_list = ['s']
mid_list = ['s']
sd_list = ['s']
fin_list = []
unsorted_list = []
scraper_list =[]
high_qual = '1080'
low_qual = '0'

def MENU():
    addDir('[B][COLOR white]Movies[/COLOR][/B]','url',1,ART + 'movies.jpg',FANART,'','','','','')
    addDir('[B][COLOR white]Latest Movie Releases[/COLOR][/B]',BASEURL2 + '/search/title?languages=en&num_votes=1000,200000&production_status=released&title_type=feature,tv_movie&sort=release_date,desc',5,ART + 'late_mov.jpg',FANART,'','','','','')
    addDir('[B][COLOR white]Movie Search[/COLOR][/B]','url',8,ART + 'search_mov.jpg',FANART,'','','','','')
    addDir('[B][COLOR white]TV Shows[/COLOR][/B]','url',2,ART + 'shows.jpg',FANART,'','','','','')
    addDir('[B][COLOR white]TV Show Search[/COLOR][/B]','url',12,ART + 'search_tv.jpg',FANART,'','','','','')   
    addDir('[B][COLOR white]IMDB Movie Playlists[/COLOR][/B]','url',50,ART + 'm_imdb.jpg',FANART,'','','','','')
    addDir('[B][COLOR white]IMDB TV Show Playlists[/COLOR][/B]','url',52,ART + 'tv_imdb.jpg',FANART,'','','','','')
    addDir('[B][COLOR white]Your IMDB Playlists[/COLOR][/B]','url',53,ART + 'y_imdb.jpg',FANART,'','','','','')
    if getmov25=='true':
        addDir('[B][COLOR white]Movies25[/COLOR][/B]','url',60,ART + 'm25.jpg',FANART,'','','','','')    
    xbmc.executebuiltin('Container.SetViewMode(50)')    


def Movies():
    addDir('[B][COLOR white]IMDB Now Playing[/COLOR][/B]',BASEURL + '/search/title?groups=now-playing-us&languages=en&title_type=feature',5,ART + 'playing.jpg',FANART,'','','','','')
    addDir('[B][COLOR white]IMDB Box Office[/COLOR][/B]',BASEURL + '/search/title?has=technical&moviemeter=,50000&num_votes=3000,&production_status=released&title_type=feature,tv_movie&sort=boxoffice_gross_us,desc',5,ART + 'boxoffice.jpg',FANART,'','','','','')
    addDir('[B][COLOR white]IMDB Box Office By Year[/COLOR][/B]','url',6,ART + 'year.jpg',FANART,'','','','','')
    addDir('[B][COLOR white]IMDB Box Office by Decade[/COLOR][/B]','url',7,ART + 'decade.jpg',FANART,'','','','','')    
    addDir('[B][COLOR white]IMDB Top 250[/COLOR][/B]',BASEURL + '/search/title?has=technical&moviemeter=,200000&num_votes=200,&production_status=released&title_type=feature,tv_movie&groups=top_250&sort=user_rating,desc',5,ART + 'top250.jpg',FANART,'','','','','')
    addDir('[B][COLOR white]IMDB Highest Rated[/COLOR][/B]',BASEURL + '/search/title?has=technical&moviemeter=,50000&num_votes=25000,&production_status=released&title_type=feature,tv_movie&sort=user_rating,desc',5,ART + 'h_rate.jpg',FANART,'','','','','')
    addDir('[B][COLOR white]IMDB Kids Zone[/COLOR][/B]',BASEURL + '/search/title?has=technical&moviemeter=,200000&num_votes=200,&production_status=released&certificates=us:g&genres=family&title_type=feature,tv_movie&sort=boxoffice_gross_us,desc',5,ART + 'kids.jpg',FANART,'','','','','')   
    addDir('[B][COLOR white]IMDB Oscar Winners[/COLOR][/B]',BASEURL + '/search/title?groups=oscar_winners&languages=en&view=advanced',5,ART + 'oscar.jpg',FANART,'','','','','')
    addDir('[B][COLOR white]IMDB All Time Top Movies[/COLOR][/B]',BASEURL + '/search/title?countries=gb,us&languages=en&num_votes=5000,&title_type=feature&view=advanced',5,ART + 'all_time.jpg',FANART,'','','','','')
    addDir('[B][COLOR white]IMDB by Genre[/COLOR][/B]','url',4,ART + 'genre.jpg',FANART,'','','','','')
    addDir('[B][COLOR blue]Search IMDB for a Movie[/COLOR][/B]','url',8,ART + 'search_mov.jpg',FANART,'','','','','')
    xbmc.executebuiltin('Container.SetViewMode(50)')
    
def TV_shows():
    addDir('[B][COLOR white]TV Shows Popular[/COLOR][/B]',BASEURL + '/search/title?has=technical&moviemeter=,50000&num_votes=1500,&title_type=tv_series,mini_series&',9,ART+'tv_pop.jpg',FANART,'','','','','')
    addDir('[B][COLOR white]Most Voted[/COLOR][/B]',BASEURL + '/search/title?has=technical&moviemeter=,50000&num_votes=1500,&title_type=tv_series,mini_series&sort=num_votes,desc',9,ART+'tv_voted.jpg',FANART,'','','','','')    
    addDir('[B][COLOR white]Highest Rated[/COLOR][/B]',BASEURL + '/search/title?has=technical&moviemeter=,50000&num_votes=25000,&title_type=tv_series,mini_series&sort=user_rating,desc',9,ART+'tv_high.jpg',FANART,'','','','','')    
    addDir('[B][COLOR white]All Time Shows[/COLOR][/B]',BASEURL + '/search/title?num_votes=5000,&sort=user_rating&title_type=tv_series',9,ART+'tv_alltime.jpg',FANART,'','','','','')
    addDir('[B][COLOR white]TV Release Date[/COLOR][/B]',BASEURL + '/search/title?num_votes=5000,&sort=release_date_us,desc&title_type=tv_series',9,ART+'tv_release.jpg',FANART,'','','','','')
    addDir('[B][COLOR white]Shows By Year[/COLOR][/B]','url',16,ART + 'tv_year.jpg',FANART,'','','','','')
    addDir('[B][COLOR white]Shows by Decade[/COLOR][/B]','url',17,ART + 'tv_dec.jpg',FANART,'','','','','') 
    addDir('[B][COLOR white]Shows by Genre[/COLOR][/B]','url',15,ART + 'tv_genre.jpg',FANART,'','','','','')
    addDir('[B][COLOR white]A to Z Shows[/COLOR][/B]',BASEURL + '/search/title?num_votes=5000,&sort=alpha,asc&start=&title_type=tv_series',9,ART+'tv_a_z.jpg',FANART,'','','','','')
    addDir('[B][COLOR blue]Search for a Show[/COLOR][/B]','url',12,ART+'search_tv.jpg',FANART,'','','','','')
    xbmc.executebuiltin('Container.SetViewMode(50)')

################IMDB Playlists#########################    
def mov_playlists():      
    addDir('[B][COLOR white]The Complete "Marvel Cinematic Universe"[/COLOR][/B]',BASEURL2 + '/list/ls071217506/',51,ART + 'm_imdb.jpg',FANART,'','','','','')
    addDir('[B][COLOR white]Movie List with ratings out of 10[/COLOR][/B]',BASEURL2 + '/list/ls000021660/',51,ART + 'm_imdb.jpg',FANART,'','','','','')
    addDir('[B][COLOR white]Best Action Movies Ever made[/COLOR][/B]',BASEURL2 + '/list/ls000120369/',51,ART + 'm_imdb.jpg',FANART,'','','','','')
    addDir('[B][COLOR white]Girly Movies List[/COLOR][/B]',BASEURL2 + '/list/ls056509051/',51,ART + 'm_imdb.jpg',FANART,'','','','','')
    addDir('[B][COLOR white]Kids Movies on Netflix[/COLOR][/B]',BASEURL2 + '/list/ls073482389/',51,ART + 'm_imdb.jpg',FANART,'','','','','')
    addDir('[B][COLOR white]Amazon Prime Instant Videos[/COLOR][/B]',BASEURL2 + '/list/ls051234103/',51,ART + 'm_imdb.jpg',FANART,'','','','','')
    addDir('[B][COLOR white]100 Best Disney Movies Ever[/COLOR][/B]',BASEURL2 + '/list/ls000422381/',51,ART + 'm_imdb.jpg',FANART,'','','','','')
    addDir('[B][COLOR white]Top 100 Gangster Movies[/COLOR][/B]',BASEURL2 + '/list/ls001818278/',51,ART + 'm_imdb.jpg',FANART,'','','','','')
    addDir('[B][COLOR white]Best Movies "Based on a True Story"[/COLOR][/B]',BASEURL2 + '/list/ls062256274/',51,ART + 'm_imdb.jpg',FANART,'','','','','')
    addDir('[B][COLOR white]Best Disaster Movies[/COLOR][/B]',BASEURL2 + '/list/ls002913604/',51,ART + 'm_imdb.jpg',FANART,'','','','','')
    addDir('[B][COLOR white]The 50 Best Teen Movies from the 2010+[/COLOR][/B]',BASEURL2 + '/list/ls031462059/',51,ART + 'm_imdb.jpg',FANART,'','','','','')
    addDir('[B][COLOR white]Best Outer Space Movies[/COLOR][/B]',BASEURL2 + '/list/ls032488294/',51,ART + 'm_imdb.jpg',FANART,'','','','','')
    addDir('[B][COLOR white]"Carry On" Movies[/COLOR][/B]',BASEURL2 + '/list/ls058169674/',51,ART + 'm_imdb.jpg',FANART,'','','','','')
    addDir('[B][COLOR white]The Name\'s Bond[/COLOR][/B]',BASEURL2 + '/list/ls006405458/',51,ART + 'm_imdb.jpg',FANART,'','','','','')    

def tv_playlists():
    addDir('[B][COLOR white]British TV (2017)[/COLOR][/B]',BASEURL2 + '/list/ls062429616/',51,ART + 'tv_imdb.jpg',FANART,'','','','','')       
    addDir('[B][COLOR white]Netflix Original Series[/COLOR][/B]',BASEURL2 + '/list/ls064243721/',51,ART + 'tv_imdb.jpg',FANART,'','','','','')
    addDir('[B][COLOR white]TV Shows to Watch (2016-2017)[/COLOR][/B]',BASEURL2 + '/list/ls031451411/',51,ART + 'tv_imdb.jpg',FANART,'','','','','')
    addDir('[B][COLOR white]Best of the BBC (2000+)[/COLOR][/B]',BASEURL2 + '/list/ls057506741/',51,ART + 'tv_imdb.jpg',FANART,'','','','','')
    addDir('[B][COLOR white]60 Best Box Sets On Netflix[/COLOR][/B]',BASEURL2 + '/list/ls063575015/',51,ART + 'tv_imdb.jpg',FANART,'','','','','')
    addDir('[B][COLOR white]Top 250 Documentary[/COLOR][/B]',BASEURL2 + '/list/ls074488634/',51,ART + 'tv_imdb.jpg',FANART,'','','','','')
    addDir('[B][COLOR white]British TV Series and Miniseries[/COLOR][/B]',BASEURL2 + '/list/ls056411356/',51,ART + 'tv_imdb.jpg',FANART,'','','','','')
    addDir('[B][COLOR white]British Crime TV Series[/COLOR][/B]',BASEURL2 + '/list/ls057604718/',51,ART + 'tv_imdb.jpg',FANART,'','','','','')
    addDir('[B][COLOR white]Action Packed Box Set TV[/COLOR][/B]',BASEURL2 + '/list/ls079345577/',51,ART + 'tv_imdb.jpg',FANART,'','','','','')
    addDir('[B][COLOR white]Top 100 Comedy[/COLOR][/B]',BASEURL2 + '/list/ls059567201/',51,ART + 'tv_imdb.jpg',FANART,'','','','','')
    addDir('[B][COLOR white]80\'s TV Shows[/COLOR][/B]',BASEURL2 + '/list/ls053390994/',51,ART + 'tv_imdb.jpg',FANART,'','','','','')
    addDir('[B][COLOR white]Space SciFi TV Shows[/COLOR][/B]',BASEURL2 + '/list/ls050385186/',51,ART + 'tv_imdb.jpg',FANART,'','','','','')
    addDir('[B][COLOR white]Detective Crime Mystery Shows[/COLOR][/B]',BASEURL2 + '/list/ls015354780/',51,ART + 'tv_imdb.jpg',FANART,'','','','','')
    addDir('[B][COLOR white]MARVEL Cinematic Universe Shows[/COLOR][/B]',BASEURL2 + '/list/ls072533741/',51,ART + 'tv_imdb.jpg',FANART,'','','','','')
    
def user_playlists():
    if m_list_name1!= '':
        if m_list_id1!= '':
            addDir('[B][COLOR white]%s[/COLOR][/B]'%m_list_name1,BASEURL2 + '/list/%s/'%m_list_id1,51,ART + 'y_imdb.jpg',FANART,'','','','','')
    if m_list_name2!= '':
        if m_list_id2!= '':
            addDir('[B][COLOR white]%s[/COLOR][/B]'%m_list_name2,BASEURL2 + '/list/%s/'%m_list_id2,51,ART + 'y_imdb.jpg',FANART,'','','','','')
    if m_list_name3!= '':
        if m_list_id3!= '':
            addDir('[B][COLOR white]%s[/COLOR][/B]'%m_list_name3,BASEURL2 + '/list/%s/'%m_list_id3,51,ART + 'y_imdb.jpg',FANART,'','','','','')
    if m_list_name4!= '':
        if m_list_id4!= '':
            addDir('[B][COLOR white]%s[/COLOR][/B]'%m_list_name4,BASEURL2 + '/list/%s/'%m_list_id4,51,ART + 'y_imdb.jpg',FANART,'','','','','')
    if m_list_name5!= '':
        if m_list_id5!= '':
            addDir('[B][COLOR white]%s[/COLOR][/B]'%m_list_name5,BASEURL2 + '/list/%s/'%m_list_id5,51,ART + 'y_imdb.jpg',FANART,'','','','','')       
    if m_list_name6!= '':
        if m_list_id6!= '':
            addDir('[B][COLOR white]%s[/COLOR][/B]'%m_list_name6,BASEURL2 + '/list/%s/'%m_list_id6,51,ART + 'y_imdb.jpg',FANART,'','','','','')
    if m_list_name7!= '':
        if m_list_id7!= '':
            addDir('[B][COLOR white]%s[/COLOR][/B]'%m_list_name7,BASEURL2 + '/list/%s/'%m_list_id7,51,ART + 'y_imdb.jpg',FANART,'','','','','')
    if m_list_name8!= '':
        if m_list_id8!= '':
            addDir('[B][COLOR white]%s[/COLOR][/B]'%m_list_name8,BASEURL2 + '/list/%s/'%m_list_id8,51,ART + 'y_imdb.jpg',FANART,'','','','','')
    if m_list_name9!= '':
        if m_list_id9!= '':
            addDir('[B][COLOR white]%s[/COLOR][/B]'%m_list_name9,BASEURL2 + '/list/%s/'%m_list_id9,51,ART + 'y_imdb.jpg',FANART,'','','','','')
    if m_list_name10!= '':
        if m_list_id10!= '':
            addDir('[B][COLOR white]%s[/COLOR][/B]'%m_list_name10,BASEURL2 + '/list/%s/'%m_list_id10,51,ART + 'y_imdb.jpg',FANART,'','','','','')
        
def Clean(name):
    name = name.replace('&#x27;',"'").replace('&#x26;','&').replace('&#xB2;','')
    return name
    
def playlist_movie(url):
    headers = {'User-Agent':User_Agent}
    listpage = url
    OPEN = requests.get(url,headers=headers,allow_redirects=False).content
    links = re.compile('class="list_item(.+?)wlb_wrapper',re.DOTALL).findall(OPEN)
    for p in links:
        #items = len(p)
        #print ':::::::::::::::'+ p
        imdb = re.compile('href="(.+?)"',re.DOTALL).findall(p)[0]
        try:
            icon = re.compile('src="(https://images-na.ssl-images-amazon.com/.+?)"',re.DOTALL).findall(p)[0]
            icon = icon.split('_')[0]
            icon = icon + 'jpg'
        except:
            icon = ICON
        
        title = re.compile('class="info">.+?href=.+?>(.+?)</a>',re.DOTALL).findall(p)[0]
        try:
            year = re.compile('<span class="year_type">.+?([0-9]{4}).+?</span>',re.DOTALL).findall(p)[0]
            
        except:
            year = '100'
        Series_chk = re.compile('<span class="year_type">(.+?)</span>',re.DOTALL).findall(p)[0]
        CHECKYEAR=int(year)            
        desc = re.compile('description.+?>(.+?)<',re.DOTALL).findall(p)[0]
        title = Clean(title)
        name = title+' ('+year+')'
        if CHECKYEAR <2018:
            if CHECKYEAR>1000:
                if 'Series' in Series_chk:
                    show=title
                    addDir('[B][COLOR white]%s[/COLOR][/B] [COLOR blue](TV Show)[/COLOR]' %name,BASEURL2+imdb,10,icon,icon,desc,show,year,'','')
                else:
                    addDir('[B][COLOR white]%s[/COLOR][/B]' %name,imdb,80,icon,icon,desc,title,year,'','')
    NP = re.compile('<div class="pagination">(.+?)</div>',re.DOTALL).findall(OPEN)
    NP2 = re.compile('<a href="(.+?)"',re.DOTALL).findall(str(NP)) 
    for url in NP2:
        url = url.split('&')[0]
        url=listpage+ url
        addDir('[B][COLOR teal]Next Page >>>[/COLOR][/B]',url,51,ART + 'nextpage.jpg',FANART,'','','','','')
    setView('movies', 'movie-view')

######### blocks_GENRES #########
def IMDB_genre():
    genres = ['action','adventure','animation','biography','comedy','crime','documentary','drama','family','fantasy',
              'film_noir','game_show','history','horror','music','mystery','romance','sci_fi','sport','thriller','war','western']
    for genre in genres:
        url = BASEURL + '/search/title?genres=%s&languages=en&num_votes=1000,200000&production_status=released&title_type=feature,tv_movie&sort=release_date,desc' %genre
        name = genre.replace('_','-').title()
        addDir('[B][COLOR white]%s[/COLOR][/B]' %name,url,5,ART + 'genre.jpg',FANART,'','','','','')
    xbmc.executebuiltin('Container.SetViewMode(50)')  

def BOX_year():
    years = ['2017','2016','2015','2014','2013','2012','2011','2010','2009','2008','2007','2006','2005','2004','2003'
              '2002','2001','2000']
    for year in years:
        url = BASEURL + '/search/title?has=technical&moviemeter=,200000&num_votes=1000,&production_status=released&year=%s,%s&title_type=feature,tv_movie&sort=boxoffice_gross_us,desc' %(year,year)
        addDir('[B][COLOR white]%s[/COLOR][/B]' %year,url,5,ART + 'year.jpg',FANART,'','','','','')
    xbmc.executebuiltin('Container.SetViewMode(50)') 
    
def BOX_Dec():
    decs = ['2010,2017','2000,2009','1990,1999','1980,1989','1970,1979','1960,1969','1950,1959','1940,1949','1930,1939','1920,1929']
    for dec in decs:
        url = BASEURL + '/search/title?release_date=%s&has=technical&moviemeter=,200000&num_votes=1000,&production_status=released&title_type=feature,tv_movie&sort=boxoffice_gross_us,desc' %dec
        name = dec.replace(',','-')
        addDir('[B][COLOR white]%s[/COLOR][/B]' %name,url,5,ART + 'decade.jpg',FANART,'','','','','')
    xbmc.executebuiltin('Container.SetViewMode(50)')     

def SHOW_genre():
    genres = ['action','adventure','animation','biography','comedy','crime','documentary','drama','family','fantasy',
              'film_noir','game_show','history','horror','music','mystery','romance','sci_fi','sport','thriller','war','western']
    for genre in genres:
        url = BASEURL + '/search/title?genres=%s&languages=en&num_votes=1000,200000&production_status=released&title_type=tv_series,mini_series&sort=release_date,desc' %genre
        name = genre.replace('_','-').title()
        addDir('[B][COLOR white]%s[/COLOR][/B]' %name,url,9,ART + 'tv_genre.jpg',FANART,'','','','','')
    xbmc.executebuiltin('Container.SetViewMode(50)')  

def SHOW_year():
    years = ['2017','2016','2015','2014','2013','2012','2011','2010','2009','2008','2007','2006','2005','2004','2003'
              '2002','2001','2000']
    for year in years:
        url = BASEURL + '/search/title?has=technical&moviemeter=,200000&num_votes=1000,&production_status=released&year=%s,%s&title_type=tv_series,mini_series&sort=num_votes,desc' %(year,year)
        addDir('[B][COLOR white]%s[/COLOR][/B]' %year,url,9,ART + 'tv_year.jpg',FANART,'','','','','')
    xbmc.executebuiltin('Container.SetViewMode(50)') 
    
def SHOW_Dec():
    decs = ['2010,2017','2000,2009','1990,1999','1980,1989','1970,1979','1960,1969','1950,1959','1940,1949','1930,1939','1920,1929']
    for dec in decs:
        url = BASEURL + '/search/title?release_date=%s&has=technical&moviemeter=,200000&num_votes=1000,&production_status=released&title_type=tv_series,mini_series&sort=num_votes,desc' %dec
        name = dec.replace(',','-')
        addDir('[B][COLOR white]%s[/COLOR][/B]' %name,url,9,ART + 'tv_dec.jpg',FANART,'','','','','')
    xbmc.executebuiltin('Container.SetViewMode(50)') 

#################################
    
def Get_IMDB(url):
    OPEN = Open_Url(url)
    match=re.compile('class="loadlate"(.+?)<p class=""',re.DOTALL).findall(OPEN)
    for item in match:
        items = len(item)
        icon = re.compile('loadlate="(.+?)"',re.DOTALL).findall(item)[0]
        icon = icon.split('_')[0]
        icon = icon + 'jpg'
        title = re.compile('v_li_tt.+?>(.+?)<',re.DOTALL).findall(item)[0]
        title=title.replace('(New and Selected)','')
        year = re.compile('class="lister-item-year text-muted unbold">(.+?)</span>',re.DOTALL).findall(item)[0]
        if ') (' in year:
            year = year.split(') ')[1]
        year = year.replace(' TV Movie','')
        name = '%s %s'  %(title,year)     
        imdb = re.compile('data-tconst="(.+?)"',re.DOTALL).findall(item)[0]
        desc = re.compile('<p class="text-muted">(.+?)</p>',re.DOTALL).findall(item)[0]  
        if metaset=='true':
            addDir2('[B][COLOR white]%s[/COLOR][/B]' %name,imdb,80,icon,items,title,year)
        else:
            addDir('[B][COLOR white]%s[/COLOR][/B]' %name,imdb,80,icon,icon,desc,title,year,'','')
    NP = re.compile('<div class="nav">(.+?)<div class="sorting">',re.DOTALL).findall(OPEN)
    NP2 = re.compile('<a href="(.+?)\&ref_=adv_nxt"',re.DOTALL).findall(str(NP)) 
    for url in NP2:
        url='http://akas.imdb.com/search/title'+ url
        addDir('[B][COLOR teal]Next Page >>>[/COLOR][/B]',url,5,ART + 'nextpage.jpg',FANART,'','','','','')
    setView('movies', 'movie-view')


def IMDB_shows(url):
        link=Open_Url(url)
        LINK=link.split('class="loadlate"')
        match=[]
        
        for p in LINK:
            try:
                iconimage = re.compile('loadlate="(.+?)"').findall(p)[0]
                url = re.compile('href="(.+?)"').findall(p)[0]
                try:url=url.split('?')[0]
                except:pass
                name = re.compile('v_li_tt"\n>(.+?)<').findall(p)[0]
                description = re.compile('<p class="text-muted">\n(.+?)<').findall(p)[0]
                year = re.compile('class="lister-item-year text-muted unbold">.+?([0-9]{4}).+?</span>').findall(p)[0]
                #year = year.split('-')[0].reaplce('(','')
                match.append([iconimage, name,url, description,year])                          
            except:pass  
        nextp=re.compile('<a href="(.+?)\&ref_=adv_nxt"').findall(link)
        try:      
                nextp1=nextp[0]
        except:
                pass       
        for iconimage, name, url, description,year in match:
            name = str(name).replace('&#xB7;','').replace('&#x27;','').replace('&#x26;','And').replace('&#x26;','And')
            iconimage1 = iconimage
            url = 'http://akas.imdb.com'+str(url)
            series = str(name).replace('&#xB7','').replace('&#x27;','').replace('&#x26;','And').replace('&#x26;','And')
            regex=re.compile('(.+?)_V1.+?.jpg')
            regex1=re.compile('(.+?).gif')
            try:
                    match = regex.search(iconimage1)
                    iconimage= '%s_V1_.SX593_SY799_.jpg'%(match.group(1))
                    fanart= '%s_V1.jpg'%(match.group(1))
            except:
                    pass
            try:    
                    match= regex1.search(iconimage1)
                    iconimage= '%s.gif'%(match.group(1))
                    fanart= '%s_V1.jpg'%(match.group(1))
            except:
                    pass
            show = name
            #print 'GW_CHK'+year
            addDir('[B][COLOR white]%s[/COLOR][/B]' %name,url,10,iconimage,fanart,description,show,year,'','')   
 
        try:
                url='http://akas.imdb.com/search/title'+str(nextp1)
                name= '[COLOR blue][B]Next Page >>[/B][/COLOR]'
                addDir(name,url,9,ART+'nextpage.jpg',FANART,'','','','','')    
        except:
                pass
        setView('movies', 'movie-view')

def TV_SEASON(url):
        #print 'testme'+title
        link=Open_Url(url)
        match = re.compile('<a href=".+?episodes\?season=(.+?)&').findall(link)
        
        url2= str(url)
        try:url2=url2.split('?')[0]
        except:pass
        for season in match:
            url = str(url2)+'episodes?season='+str(season)
            #print url
            name2 = 'Season '+str(season)
            xbmcplugin.addSortMethod(int(sys.argv[1]), xbmcplugin.SORT_METHOD_VIDEO_TITLE)
            addDir('[B][COLOR white]%s[/COLOR][/B]' %name2,url,11,iconimage,iconimage,description,title,year,'','')  
        setView('tvshows', 'show-view')
            
def TV_EPISODE(name,url,iconimage,description,title,year):
        
        #print 'FUCK> '+ title
        links=Open_Url(url)
        p=links.split('itemprop="url">')
        #series1=series
        #replacementicon=series
        icon=iconimage
        for link in p:
                #print p
	        if 'itemprop="episodes"' in link:
                        try:
                            icons=link.split('src="')[1]
                            iconimage=icons.split('"')[0]
                        except:iconimage=''    
		        ep=link.split('<div>')[1]
		        _name=link.split('itemprop="name">')[1]
		        des=link.split('<div class="item_description" itemprop="description">')[1]
		        description=des.split('</div>')[0]
		        name=_name.split('</a>')[0]
		        episode=ep.split('</div>')[0]
		        if iconimage.endswith(".png"):
		                iconimage = str(icon)
		        description= str(description).replace('&#700;','').replace('">','')
		        iconimage1= iconimage
		        episode='['+str(episode).replace('26,','26').replace('25,','25').replace('24,','24').replace('23,','23').replace('22,','22').replace('21,','21').replace('20,','20').replace('19,','19').replace('18,','18').replace('17,','17').replace('16,','16').replace('15,','15').replace('14,','14').replace('13,','13').replace('12,','12').replace('11,','11').replace('10,','10').replace('9,','09').replace('8,','08').replace('7,','07').replace('6,','06').replace('5,','05').replace('4,','04').replace('3,','03').replace('2,','02').replace('1,','01').replace('p26','26').replace('p25','25').replace('p24','24').replace('p23','23').replace('p22','22').replace('p21','p21').replace('p20','20').replace('p19','19').replace('p18','18').replace('p17','17').replace('p16','16').replace('p15','15').replace('p14','14').replace('p13','13').replace('p12','12').replace('p11','11').replace('p10','10').replace('p9','09').replace('p8','08').replace('p7','07').replace('p6','06').replace('p5','05').replace('p4','04').replace('p3','03').replace('p2','02').replace('p1','01')+']'
		        name= str(episode)+' '+str(name).replace('&#xB7;','').replace('&#x27;','').replace('&#x26;','And')
		        #series = str(episode)+' '+str(series1)
		        regex=re.compile('(.+?)_V1.+?.jpg')
		        regex1=re.compile('(.+?).gif')
		        try:
		                match = regex.search(iconimage1)
		                iconimage= '%s_V1_.SX593_SY799_.jpg'%(match.group(1))
		        except:
		                pass
		        try:    
		                match= regex1.search(iconimage1)
		                iconimage= '%s.gif'%(match.group(1))
		        except:
		                pass
		        addDir('[B][COLOR white]%s[/COLOR][/B]' %name,title,90,iconimage,iconimage,description,title,year,'',episode)
                print name                
        setView('episodes', 'epi-view')     


def SearchMOV():
        keyb = xbmc.Keyboard('', 'Search for a Movie')
        keyb.doModal()
        if (keyb.isConfirmed()):
                search = keyb.getText().replace(' ','%20')
                url  = BASEURL + '/search/title?languages=en&production_status=released&title=' + search + '&title_type=feature'
                Get_IMDB(url)

def SearchTV():
        keyb = xbmc.Keyboard('', 'Search for a Show')
        keyb.doModal()
        if (keyb.isConfirmed()):
                search = keyb.getText().replace(' ','%20')
                url  = BASEURL + '/search/title?languages=en&production_status=released&title=' + search + '&title_type=tv_series'
                IMDB_shows(url)               
##################################################################################
def M25MENU():
    addDir('[B][COLOR white]New Releases[/COLOR][/B]',PROXY +'/browse.php?u=http://5movies.to/new-release/',61,ART + 'm_nrel.jpg',FANART,'','','','','') 
    addDir('[B][COLOR white]Latest Added[/COLOR][/B]',PROXY +'/browse.php?u=http://5movies.to/latest-added/',61,ART + 'm_lad.jpg',FANART,'','','','','') 
    addDir('[B][COLOR white]Featured[/COLOR][/B]',PROXY +'/browse.php?u=http://5movies.to/featured/',61,ART + 'm_feat.jpg',FANART,'','','','','')
    addDir('[B][COLOR white]Latest HD[/COLOR][/B]',PROXY +'/browse.php?u=http://5movies.to/latest-hd/',61,ART + 'm_lathd.jpg',FANART,'','','','','')
    addDir('[B][COLOR white]Latest TS[/COLOR][/B]',PROXY +'/browse.php?u=http://5movies.to/latest-ts/',61,ART + 'm_latts.jpg',FANART,'','','','','')
    addDir('[B][COLOR white]Most Popular[/COLOR][/B]',PROXY +'/browse.php?u=http://5movies.to/most-popular/',61,ART + 'm_mpop.jpg',FANART,'','','','','')
    addDir('[B][COLOR white]Popular Today[/COLOR][/B]',PROXY +'/browse.php?u=http://5movies.to/popular-today/',61,ART + 'm_2day.jpg',FANART,'','','','','')
    addDir('[B][COLOR white]Top Rated[/COLOR][/B]',PROXY +'/browse.php?u=http://5movies.to/top-rated/',61,ART + 'm_rated.jpg',FANART,'','','','','')
    addDir('[B][COLOR white]Most Rated[/COLOR][/B]',PROXY +'/browse.php?u=http://5movies.to/most-rated/',61,ART + 'm_srat.jpg',FANART,'','','','','')
    addDir('[B][COLOR white]Genres[/COLOR][/B]','url',65,ART + 'm_gen.jpg',FANART,'','','','','')
    addDir('[B][COLOR white]A - Z[/COLOR][/B]',PROXY+'/browse.php?u=http://5movies.to',66,ART + 'm_az.jpg',FANART,'','','','','')
    addDir('[B][COLOR white]Release Year[/COLOR][/B]',PROXY+'/browse.php?u=http://5movies.to',67,ART + 'm_ryear.jpg',FANART,'','','','','')
    
def M25_content(url):
    ref = url.split('/browse')[0]
    headers = {'User_Agent':User_Agent,'referer':ref}
    OPEN = requests.get(url, headers=headers).content
    Regex = re.compile('<div class="movie-list".+?src="(.+?)" alt="(.+?)">',re.DOTALL).findall(OPEN)
    for icon,name in Regex:
        items = len(Regex)
        title = name.split(' (')[0]
        year = name.split(' (')[1].replace(')','')
        icon = icon + '|' + urllib.urlencode(headers)
        try:
           addDir2('[B][COLOR white]%s[/COLOR][/B]' %name,'url',80,ref+icon,items,title,year)
        except:pass
    NP = re.compile('<div class="pagination">(.+?)</div>',re.DOTALL).findall(OPEN)
    NP2 = re.compile("href='(.+?)'>(.+?)</a>",re.DOTALL).findall(str(NP))        
    for url,npage in NP2:
        if 'Next' in npage:    
            addDir('[COLOR blue][B]Next Page >>[/B][/COLOR]',PROXY + url,61,ART+'m_next.jpg',FANART,'','','','','')
    setView('movies', 'movie-view')


def M25_genre():
    genres = ['action','adventure','animation','biography','comedy','crime','documentary','drama','family','fantasy',
              'history','horror','music','musical','mystery','romance','sci-fi','short','sport','thriller','war','western']
    for genre in genres:
        url = PROXY + '/browse.php?u=http://5movies.to/' + genre
        name = genre.title()
        addDir('[B][COLOR white]%s[/COLOR][/B]' %name,url,61,ART + 'm_gen.jpg',FANART,'','','','','')
    xbmc.executebuiltin('Container.SetViewMode(50)') 

def M25_a_z(url):
    ref = url.split('/browse')[0]
    headers = {'User_Agent':User_Agent,'referer':ref}
    OPEN = requests.get(url, headers=headers).content
    Regex = re.compile('>A-Z(.+?)</ul>',re.DOTALL).findall(OPEN)
    Regex2 = re.compile('href="(.+?)".+?title="(.+?)"',re.DOTALL).findall(str(Regex))
    for url,name in Regex2:
        addDir('[B][COLOR white]%s[/COLOR][/B]' %name,ref + url,61,ART + 'm_az.jpg',FANART,'','','','','')
    xbmc.executebuiltin('Container.SetViewMode(50)') 

def M25_year(url):
    ref = url.split('/browse')[0]
    headers = {'User_Agent':User_Agent,'referer':ref}
    OPEN = requests.get(url, headers=headers).content
    Regex = re.compile('>Release Year(.+?)</ul>',re.DOTALL).findall(OPEN)
    Regex2 = re.compile('href="(.+?)".+?title="(.+?)"',re.DOTALL).findall(str(Regex))
    for url,name in Regex2:
        addDir('[B][COLOR white]%s[/COLOR][/B]' %name,ref + url,61,ART + 'm_ryear.jpg',FANART,'','','','','')
    xbmc.executebuiltin('Container.SetViewMode(50)') 
    
##################################################################################
def sort_qual(link):
	qual_return = str(link["quality"]).lower().replace('0p','0').replace(' ','')
	if qual_return=='sd': qual_check = '240';qual_letter='i';name2 = link["source"] + " - " + link["scraper"] + " (" + link["quality"] + ")";sd_list.append('1')
	elif qual_return=='240': qual_check = '240';qual_letter='i'; name2 = link["source"] + " - " + link["scraper"] + " (" + link["quality"] + ")";sd_list.append('1')
	elif qual_return=='cam': qual_check = '120';qual_letter='j'; name2 = link["source"] + " - " + link["scraper"] + " (" + link["quality"] + ")";sd_list.append('1')
	elif qual_return=='360': qual_check = '360';qual_letter='h'; name2 = link["source"] + " - " + link["scraper"] + " (" + link["quality"] + ")";sd_list.append('1')
	elif qual_return=='480': qual_check = '480';qual_letter='g'; name2 = link["source"] + " - " + link["scraper"] + " (" + link["quality"] + ")";mid_list.append('1')
	elif qual_return=='560': qual_check = '560';qual_letter='f'; name2 = ' '+link["source"] + " - " + link["scraper"] + " (" + link["quality"] + ")";mid_list.append('1')
	elif qual_return=='720': qual_check = '720';qual_letter='c'; name2 = ' '+link["source"] + " - " + link["scraper"] + " (" + link["quality"] + ")";mid_list.append('1')
	elif qual_return=='hd': qual_check = '1080';qual_letter='d'; name2 = ' '+link["source"] + " - " + link["scraper"] + " (" + link["quality"] + ")";hd_list.append('1')
	elif qual_return=='dvd': qual_check = '1080';qual_letter='e'; name2 = ' '+link["source"] + " - " + link["scraper"] + " (" + link["quality"] + ")";hd_list.append('1')
	elif qual_return=='bluray': qual_check = '1080';qual_letter='b'; name2 = ' '+link["source"] + " - " + link["scraper"] + " (" + link["quality"] + ")";hd_list.append('1')
	elif qual_return=='1080': qual_check = '1080';qual_letter='a'; name2 = ' '+link["source"] + " - " + link["scraper"] + " (" + link["quality"] + ")";hd_list.append('1')
	else: qual_check='240';qual_letter='i';name2 = str(link["source"]) + " - " + str(link["scraper"]) + " (" + str(link["quality"]) + ")";sd_list.append('1')
	unsorted_list.append({'name2':name2,'quality':qual_check,'letter':qual_letter,'link':link})
	
def return_links(name,populator):
	dandyscraper_no = []
	dandyscraper_folder = xbmc.translatePath('special://home/addons/script.module.dandyscrapers/lib/dandyscrapers/scraperplugins/')
	for Root,Dir,Files in os.walk(dandyscraper_folder):
		for File in Files:
			if File.endswith('.py'):
				if not '__' in File:
					dandyscraper_no.append('1')
	result = 0
	for scraper_links in populator():
		scraper_list.append('a')
		if scraper_links != None:
			for link in scraper_links:
				if dp.iscanceled():
					return
				fin_list.extend('a')
				dp.update(100/int(len(dandyscraper_no))*int(len(scraper_list)),'Cancelling will display results so far',"Results : ("+str(int(len(hd_list)-1))+ "/"+str(int(len(mid_list)-1))+ "/"+str(int(len(sd_list)-1))+')','Scrapers left to run: '+str(int(len(dandyscraper_no))-int(len(scraper_list)))+' of '+str(len(dandyscraper_no)))
				if dp.iscanceled():
					return
				sort_qual(link)
	sorted_list = sorted(unsorted_list, key = lambda unsorted_link: unsorted_link['letter'])
	for item in sorted_list:
			qual_check = item['quality']
			name2 = item['name2']
			link = item['link']
			if int(high_qual)>=int(qual_check)>=int(low_qual):
				addDir('[B][COLOR white]%s[/COLOR][/B]' %name2,str(link['url']),100,iconimage,iconimage,name,'','','','')
				result+=1
			else:
				for host in Hosts:
					if str(host) in str(link["source"].lower().replace(' ','')):
						addDir('[B][COLOR white]%s[/COLOR][/B]' %name2,str(link['url']),100,iconimage,iconimage,name,'','','','')
						result+=1
					else:
						pass
			if result == 0:
				addDir('No links',100,iconimage,iconimage,'','','','','')
				#process.PLAY('Try lowering in settings','',100,'','','','')
				#process.PLAY('#####################','',100,'','','','')
				#process.PLAY('Open Settings Menu','',100,'','','','')
                
def scrape_movie(name,url,title,year):
    if url.startswith('tt'):
        imdb=url
    else: imdb=''        
    dp.create('Initiating DandyScrapers')
    title = title.replace("'","").replace(":","").replace("- ","").replace("+"," ")
    year = year.replace('(','').replace(')','')
    #imdb = ''
    print ':::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::'
    print 'Movie Scrape : Title:%s  Year:%s  IMDB:%s' %(title,year,imdb)
    print ':::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::'
    from dandyscrapers import scrape_movie
    try:
        populator = scrape_movie(title, year, imdb, timeout=60000)
    except:
        return
    return_links(name,populator)

def scrape_episode(name,url,title,year,episode):
    #name = name.replace('[B][COLOR white]','').replace('[/COLOR][/B]','').replace("'","").replace(":","").replace("- ","")
    show_year = ''
    imdb = ''
    season = episode.split(' ')[0].replace('[S','')
    if season.startswith('0'):
        season = season.split('0')[1]
    episode = episode.split(' ')[1].split(']')[0].replace('E','')
    if episode.startswith('0'):
        episode = episode.split('0')[1]
    print ':::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::'
    print 'Show scrape : Show:%s  Season:%s  Episode:%s  YEAR:%s' %(title,season,episode,year)
    print ':::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::'
    from dandyscrapers import scrape_episode
    progress = []
    item = []
    dp.create('Initiating DandyScrapers')
    try:
        populator = scrape_episode(title, show_year, year, season, episode,imdb,'', timeout=60000)
    except:
        return
    return_links(name,populator)    
    
#####################################################################################    
def RESOLVE(url): 
    send2log(url)
    if 'vidlox' in url:
        OPEN = Open_Url(url)
        url = re.compile('master.m3u8","(.+?)"',re.DOTALL).findall(OPEN)[0]
        liz = xbmcgui.ListItem(name, iconImage='DefaultVideo.png', thumbnailImage=iconimage)
        liz.setInfo(type='Video', infoLabels={"Title": description})
        liz.setProperty("IsPlayable","true")
        liz.setPath(url)
        xbmcplugin.setResolvedUrl(int(sys.argv[1]), True, liz)        
    else:
        try:
            stream_url = evaluate(url)
            #print 'ATTEMPTING TO PLAY >'+stream_url
            liz = xbmcgui.ListItem(name, iconImage='DefaultVideo.png', thumbnailImage=iconimage)
            liz.setInfo(type='Video', infoLabels={"Title": description})
            liz.setProperty("IsPlayable","true")
            liz.setPath(stream_url)
            xbmcplugin.setResolvedUrl(int(sys.argv[1]), True, liz)
        except: pass     

def evaluate(host):
    if 'googleapis.com' in host:
        host=host
    # elif 'googleusercontent.com' in host:   ##use resolver else 17+ dont play native
        # host = host
    elif 'str10.vidoza' in host:
        host = host
    elif 'google.com/videoplayback' in host:
        host=host
    elif urlresolver.HostedMediaFile(host):
        host = urlresolver.resolve(host)
    else:
        host=host
    
    return host



def OPEN_UrlRez():
        xbmcaddon.Addon('script.module.urlresolver').openSettings()

def addon_settings():
    xbmcaddon.Addon().openSettings()

def dandy_settings():
    xbmcaddon.Addon('script.module.dandyscrapers').openSettings()  

def clear_cache():
    dialog = xbmcgui.Dialog()
    dialog.yesno(addon_name, "Clear Scraper Cache?")
    import dandyscrapers
    dandyscrapers.clear_cache()

def send2log(Txt):
    print ':::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::'
    print ':                                                                               :'
    print ':   ***                                                                         :'
    print ':   ***      LOG string:   >%s<  ***'  %(str(Txt))
    print ':   ***                                                                         :'
    print ':                                                                               :'
    print ':::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::'
    return 
    
def get_params():
	param=[]
	paramstring=sys.argv[2]
	if len(paramstring)>=2:
		params=sys.argv[2]
		cleanedparams=params.replace('?','')
		if (params[len(params)-1]=='/'):
			params=params[0:len(params)-2]
		pairsofparams=cleanedparams.split('&')
		param={}
		for i in range(len(pairsofparams)):
			splitparams={}
			splitparams=pairsofparams[i].split('=')
			if (len(splitparams))==2:
				param[splitparams[0]]=splitparams[1]
	return param

def Open_Url(url):
    headers = {}
    headers['User-Agent'] = User_Agent
    link = s.get(url, headers=headers).text
    link = link.encode('ascii', 'ignore')
    return link
    
def addDir(name,url,mode,iconimage,fanart,description,title, year, season, episode):
	u=sys.argv[0]+"?url="+urllib.quote_plus(url)+"&mode="+str(mode)+"&name="+urllib.quote_plus(name)+"&iconimage="+urllib.quote_plus(iconimage)+"&description="+urllib.quote_plus(description)+"&title="+urllib.quote_plus(title)+"&year="+urllib.quote_plus(year)+"&season="+urllib.quote_plus(season)+"&episode="+urllib.quote_plus(episode)
	ok=True
	liz=xbmcgui.ListItem(name, iconImage="DefaultFolder.png", thumbnailImage=iconimage)
	liz.setInfo( type="Video", infoLabels={"Title": name,"Plot":description})
	liz.setProperty('fanart_image', fanart)
	if mode==100 or mode==101:
		liz.setProperty("IsPlayable","true")
		ok=xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=u,listitem=liz,isFolder=False)
	else:
		ok=xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=u,listitem=liz,isFolder=True)
	return ok
    
def addDir2(name,url,mode,iconimage,itemcount,title,year):
        name = name.replace('[B][COLOR white]','').replace('[/COLOR][/B]','')
        splitName=name.partition('(')
        simplename=""
        simpleyear=""
        if len(splitName)>0:
            simplename=splitName[0]
            simpleyear=splitName[2].partition(')')
        if len(simpleyear)>0:
            simpleyear=simpleyear[0]
        mg = eval(base64.b64decode('bWV0YWhhbmRsZXJzLk1ldGFEYXRhKHRtZGJfYXBpX2tleT0iMzZjMWM1OWYwNTI0YTYzZTc3MmI5MGMzNzc4ZmIwOTciKQ=='))
        meta = mg.get_meta('movie', name=simplename ,year=simpleyear)
        if meta['cover_url']=='':
            try:
                meta['cover_url']=iconimage
            except:
                meta['cover_url']=iconimage
        name = '[B][COLOR white]' + name + '[/COLOR][/B]'
        meta['title'] = name
        u=sys.argv[0]+"?url="+urllib.quote_plus(url)+"&mode="+str(mode)+"&name="+urllib.quote_plus(name)+"&iconimage="+urllib.quote_plus(iconimage)+"&title="+urllib.quote_plus(title)+"&year="+urllib.quote_plus(year)
        ok=True
        liz=xbmcgui.ListItem(name, iconImage=meta['cover_url'], thumbnailImage=meta['cover_url'])
        liz.setInfo( type="Video", infoLabels= meta )
        contextMenuItems = []
        contextMenuItems.append(('Movie Information', 'XBMC.Action(Info)'))
        if meta['trailer']:
                contextMenuItems.append(('Play Trailer', 'XBMC.RunPlugin(%s)' % addon.build_plugin_url({'mode': 99, 'url':meta['trailer']})))
        liz.addContextMenuItems(contextMenuItems, replaceItems=False)
        if not meta['backdrop_url'] == '':
                liz.setProperty('fanart_image', meta['backdrop_url'])
        else: liz.setProperty('fanart_image',FANART)
        if mode==100 or mode==101:
            liz.setProperty("IsPlayable","true")
            ok=xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=u,listitem=liz,isFolder=False,totalItems=itemcount)
        else:
             ok=xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=u,listitem=liz,isFolder=True,totalItems=itemcount)
        return ok

def notification(title, message, icon):
        addon.show_small_popup( addon.get_name(), message.title(), 5000, icon)
        return
    
def setView(content, viewType):
    ''' Why recode whats allready written and works well,
    Thanks go to Eldrado for it '''
    if content:
        xbmcplugin.setContent(int(sys.argv[1]), content)
    if addon.get_setting('auto-view') == 'true':

        print addon.get_setting(viewType)
        if addon.get_setting(viewType) == 'Info':
            VT = '504'
        elif addon.get_setting(viewType) == 'Info2':
            VT = '503'
        elif addon.get_setting(viewType) == 'Info3':
            VT = '515'
        elif addon.get_setting(viewType) == 'Fanart':
            VT = '508'
        elif addon.get_setting(viewType) == 'Poster Wrap':
            VT = '501'
        elif addon.get_setting(viewType) == 'Big List':
            VT = '51'
        elif addon.get_setting(viewType) == 'Low List':
            VT = '724'
        elif addon.get_setting(viewType) == 'List':
            VT = '50'
        elif addon.get_setting(viewType) == 'Default Menu View':
            VT = addon.get_setting('default-view1')
        elif addon.get_setting(viewType) == 'Default TV Shows View':
            VT = addon.get_setting('default-view2')
        elif addon.get_setting(viewType) == 'Default Episodes View':
            VT = addon.get_setting('default-view3')
        elif addon.get_setting(viewType) == 'Default Movies View':
            VT = addon.get_setting('default-view4')
        elif addon.get_setting(viewType) == 'Default Docs View':
            VT = addon.get_setting('default-view5')
        elif addon.get_setting(viewType) == 'Default Cartoons View':
            VT = addon.get_setting('default-view6')
        elif addon.get_setting(viewType) == 'Default Anime View':
            VT = addon.get_setting('default-view7')

        print viewType
        print VT
        
        xbmc.executebuiltin("Container.SetViewMode(%s)" % ( int(VT) ) )

    xbmcplugin.addSortMethod( handle=int( sys.argv[ 1 ] ), sortMethod=xbmcplugin.SORT_METHOD_UNSORTED )
    xbmcplugin.addSortMethod( handle=int( sys.argv[ 1 ] ), sortMethod=xbmcplugin.SORT_METHOD_LABEL )
    xbmcplugin.addSortMethod( handle=int( sys.argv[ 1 ] ), sortMethod=xbmcplugin.SORT_METHOD_VIDEO_RATING )
    xbmcplugin.addSortMethod( handle=int( sys.argv[ 1 ] ), sortMethod=xbmcplugin.SORT_METHOD_DATE )
    xbmcplugin.addSortMethod( handle=int( sys.argv[ 1 ] ), sortMethod=xbmcplugin.SORT_METHOD_PROGRAM_COUNT )
    xbmcplugin.addSortMethod( handle=int( sys.argv[ 1 ] ), sortMethod=xbmcplugin.SORT_METHOD_VIDEO_RUNTIME )
    xbmcplugin.addSortMethod( handle=int( sys.argv[ 1 ] ), sortMethod=xbmcplugin.SORT_METHOD_GENRE )
    xbmcplugin.addSortMethod( handle=int( sys.argv[ 1 ] ), sortMethod=xbmcplugin.SORT_METHOD_MPAA_RATING )



params=get_params()
url=None
name=None
mode=None
iconimage=None
description=None




try:
	url=urllib.unquote_plus(params["url"])
except:
	pass
try:
	name=urllib.unquote_plus(params["name"])
except:
	pass
try:
	iconimage=urllib.unquote_plus(params["iconimage"])
except:
	pass
try:
	mode=int(params["mode"])
except:
	pass
try:
	description=urllib.unquote_plus(params["description"])
except:
	pass
try:
    title=urllib.unquote_plus(params["title"])
except:
    pass        
try:
    year=urllib.unquote_plus(params["year"])
except:
    pass
try:
    season=urllib.unquote_plus(params["season"])
except:
    pass
        
try:
    episode=urllib.unquote_plus(params["episode"])
except:
    pass

if mode==None or url==None or len(url)<1 : MENU()
elif mode == 1 : Movies()
elif mode == 2 : TV_shows()
elif mode == 4 : IMDB_genre()
elif mode == 5 : Get_IMDB(url)
elif mode == 6 : BOX_year()
elif mode == 7 : BOX_Dec()
elif mode == 8 : SearchMOV()
elif mode == 9 : IMDB_shows(url)
elif mode == 10: TV_SEASON(url) 
elif mode == 11: TV_EPISODE(name,url,iconimage,description,title,year)
elif mode == 12: SearchTV() 
elif mode == 15 : SHOW_genre()
elif mode == 16 : SHOW_year()
elif mode == 17 : SHOW_Dec()
elif mode == 50: mov_playlists()
elif mode == 51: playlist_movie(url)
elif mode == 52: tv_playlists()
elif mode == 53: user_playlists()
elif mode == 60: M25MENU()
elif mode == 61: M25_content(url)
elif mode == 65: M25_genre()
elif mode == 66: M25_a_z(url)
elif mode == 67: M25_year(url)
elif mode == 80: scrape_movie(name,url,title,year)
elif mode == 90: scrape_episode(name,url,title,year,episode)
elif mode ==100: RESOLVE(url)
elif mode == 200: OPEN_UrlRez()
elif mode == 201: addon_settings()
elif mode == 202: dandy_settings()
elif mode == 203: clear_cache()
xbmcplugin.endOfDirectory(int(sys.argv[1]))