Sandbird / TorrentLeech V5 Enhancer

// ==UserScript==
// @name        TorrentLeech V5 Enhancer
// @namespace   https://openuserjs.org/scripts/Sandbird/TorrentLeech_V5_Enhancer
// @description Enhance TorrentLeech
// @updateURL https://openuserjs.org/meta/Sandbird/TorrentLeech_V5_Enhancer.meta.js
// @include  https://torrentleech.org/torrents/*
// @include  https://www.torrentleech.org/torrents/*
// @include  https://torrentleech.cc/torrents/*
// @include  https://www.torrentleech.cc/torrents/*
// @resource trakt_btn https://rawgit.com/Sandbird/TL/master/tr.png
// @resource trakt_btn_on https://rawgit.com/Sandbird/TL/master/tr_on.png
// @resource info_btn https://rawgit.com/Sandbird/TL/master/i.png
// @resource info_btn_on https://rawgit.com/Sandbird/TL/master/i_on.png
// @resource copy_btn https://rawgit.com/Sandbird/TL/master/c.png
// @resource copy_btn_on https://rawgit.com/Sandbird/TL/master/c_on.png
// @resource trailer_btn https://rawgit.com/Sandbird/TL/master/t.png
// @resource trailer_btn_on https://rawgit.com/Sandbird/TL/master/t_on.png
// @resource navBAR https://rawgit.com/Sandbird/TL/master/AdminLTE.min.css
// @require  http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js
// @require  http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js
// @require  https://rawgit.com/Sandbird/TL/master/app.min.js
// @require  https://raw.githubusercontent.com/overlib/overlib/master/overlib.js
// @require  https://raw.githubusercontent.com/Sandbird/TL/master/jquery-multidownload.js
// @run-at  document-start
// @grant   GM_getValue
// @grant   GM_setValue
// @grant   GM_getResourceURL
// @grant   GM_getResourceText
// @grant   GM_xmlhttpRequest
// @grant   GM_addStyle
// @version 2.8
// @license MIT
// ==/UserScript==

this.$ = this.jQuery = jQuery.noConflict(true);
var navBAR = GM_getResourceText ("navBAR");
GM_addStyle (navBAR);

function button(name, src, rollover){
        this.type = name;
        this.src = src;
        this.rollover = rollover;
}
var traktv = new button('traktv' ,GM_getResourceURL('trakt_btn') ,GM_getResourceURL('trakt_btn_on'));
var info = new button('info' ,GM_getResourceURL('info_btn') ,GM_getResourceURL('info_btn_on'));
var copy = new button('copy' ,GM_getResourceURL('copy_btn') ,GM_getResourceURL('copy_btn_on'));
var trailer = new button('trailer' ,GM_getResourceURL('trailer_btn') ,GM_getResourceURL('trailer_btn_on'));
//var episodes = new button('episodes' ,GM_getResourceURL('episodes_btn') ,GM_getResourceURL('episodesRl_btn'));
var fixed_words = Array('INTERNAL' , 'iNTERNAL' ,'READNFO' ,'NFO' ,'XBLA' ,'XBOX360','GERMAN','USA', 'NDS' ,'Update' ,
                        'Edition' ,'MULTi9' ,'MULTi7' ,'MULTi5' ,'MULTi2' ,'MULTi1' ,'XBLA' ,'Proper' ,
                        'JTAG' ,'PS3' ,'EUR' ,'DLC' ,'PL' ,'WII' ,'NGC' ,'FIX' ,'CRACK' ,'WORKING' ,
                        'NTSC' ,'Real' ,'DVDR' ,'RC' ,'BDRip' ,'TS' ,'RF' ,'PAL' ,'NORDiC' ,'UNRATED',
                        'WEBRiP', 'DVDRip', 'HDRip', 'BluRay', 'Blu-ray', 'HDTV' ,'HDCAM',
                        '720p BluRay' , '1080p BluRay', '720p', '1080p', '2160p', 'label-danger');

var buttons_collection = [traktv,
                          info,
                          copy,
                          trailer
                          ];

function addStyle(css) {
	var newstyle = document.createElement("style");
	newstyle.setAttribute("type", "text/css");
	newstyle.appendChild(document.createTextNode(css));
	document.getElementsByTagName("head")[0].appendChild(newstyle);
}
function getType(category_value){
  switch(category_value){
          case 1: case 8: case 9: case 10: case 11: case 12: case 13: case 14: case 15: case 29: case 37: case 43:
                  return 'cat_movies';
          case 2: case 26: case 27: case 32:
                  return 'cat_tv';
          case 3: case 17: case 18: case 19: case 20: case 21: case 22: case 28: case 30:
                  return 'cat_games';
  }
}
function inRange(x, min, max) {
    return min <= x && x <= max;
}
function splitter(string, type){
    var result = "";
    var split_str = string.split(' ');
    for (var index in split_str){
        if(type == 'cat_tv')
            if(parseInt(split_str[index],10) > 10 ){
                    result = (split_str.slice(0,index)).join(" ");
                    splitter(result, type);
                    break;
                }
        if(split_str[index].toLowerCase() == "update"){
             result = (split_str.slice(0,index)).join(" ");
             splitter(result, type);
             break;
        }
        if(split_str[index].charAt(0).toLocaleLowerCase() == 'v' && !isNaN(split_str[index].charAt(1))){
            result = (split_str.slice(0,index)).join(" ");
            splitter(result, type);
            break;
        }
        if(split_str[index].indexOf('-') != -1){
            result = (split_str.slice(0,index)).join(" ");
            splitter(result, type);
            break;
        }

    }
    if(result.length > 0)
       return result;
    else
        return string;


}
function cleanName2(rawName, type){
    var name = "";
    var tempName =  splitter(rawName, type);
    var split_name = tempName.split(" ");
        //remove fixed words
        for(var j = 0; j < split_name.length; j++){
                var found = false;
                for(var k = 0; k < fixed_words.length; k++){
                   if(fixed_words[k].toLowerCase() == split_name[j].toLowerCase()){
                           found = true;
                           break;
                   }
                }
                if(found)
                  delete split_name[j];
        }
        //special case filter
        for (var index in split_name){
                if(isNaN(split_name[index]) &&
                   isNaN(split_name[index].charAt(0)) &&
                   split_name[index].indexOf("(") == -1){
                                if(type == 'tv')
                                        if(split_name[index].indexOf("E") != -1 && split_name[index].indexOf("S") != -1)
                                                break;
                                name += split_name[index] + " ";
                }
                else if(!isNaN(split_name[index])){  //handler for numbers in the name
                        if(type == 'movies')
                                if(parseInt(split_name[index],10) > 10 )
                                        break;

                        name += split_name[index] + " ";
                }
                else
                        break;
        }
        if(type== 'tv')
           return name.slice(0, - 1);
        else
      return $.trim(name);
}
function openImdb(name, type){

        var movie_name = cleanName2(name, type);
        window.open('http://www.imdb.com/find?s=tt&q=' + movie_name);

 //http://www.imdbapi.com/?t=movie name --- get json respons with imdb id
 //http://www.imdb.com/find?s=tt&q=movie name  --- takes you to the movie page or to results
}
function opentraktTV(name , type){
        var showtype;
        var tv_name = cleanName2(name, type);
        if(type== 'tv'){
        	showtype = 'shows';
        }else if (type== 'movies'){
        	showtype = 'movies';
        }
        window.open('https://trakt.tv/search/'+showtype+'?query=' + tv_name);

 //http://www.tv.com/search?type=11&stype=all&tag=search%3Bforums&q=tv show name
}
function openTv(name , type){

        var tv_name = cleanName2(name, type);
        window.open('https://www.tvmaze.com/search?q=' + tv_name);

 //http://www.tv.com/search?type=11&stype=all&tag=search%3Bforums&q=tv show name
}
function openEpisodes(name, type){

        var episode_name = cleanName2(name, type);
        window.open('http://www.torrentleech.org/torrents/browse/index/query/'+ episode_name + '/facets/e8044d_877b75');

//www.torrentleech.org/torrents/browse/index/query/The+Big+Bang+Theory/facets/e8044d_877b75
}
function openGamePlay(name, type){

        var game_name = cleanName2(name, type);
        window.open('http://www.youtube.com/results?search_query='+ game_name + " gameplay");
//http://www.youtube.com/results?search_query=game name
}
function openTrailer(name, type){

        var movie_name = cleanName2(name, type);
        window.open('http://www.youtube.com/results?search_query='+ movie_name + " trailer");
//http://www.youtube.com/results?search_query=game name
}
function openGameReview(name, type){

        var game_name = cleanName2(name, type);
        //window.open('http://www.gamespot.com/search/?qs='+ game_name);
        window.open('http://www.rlslog.net/?s='+ game_name +'&sbutt=Go');

//http://www.gamespot.com/search/?qs=
}
function store(name, val) {
    if (typeof (Storage) !== "undefined") {
        localStorage.setItem(name, val);
    } else {
        window.alert('Please use a modern browser to properly view this template!');
    }
}
function get(name) {
    if (typeof (Storage) !== "undefined") {
        return localStorage.getItem(name);
    } else {
        window.alert('Please use a modern browser to properly view this template!');
    }
}
function addColour(whatTodo) {
    $('div[class = "icell seeders"]').each(function(){
        var snum = $(this).html();
        if( $(snum).hasClass('seederDiv') ){
            snum = $(this).find('.seederDiv').html();
        }
        var sstyle = '';
        var stitle = '';
        var spre = 'color';
        if(inRange(snum, 0, 50)) {
            sstyle = 'style="color:#D9D9D9"';
            stitle = '#D9D9D9';
        }
        else if(inRange(snum, 51, 100)) {
            sstyle = 'style="color:#f5efd2"';
            stitle = '#f5efd2';
        }
        else if(inRange(snum, 101, 200)) {
            sstyle = 'style="color:#c0eca9"';
            stitle = '#c0eca9';
        }
        else if(inRange(snum, 201, 300)) {
            sstyle = 'style="color:#82e3af"';
            stitle = '#82e3af';
        }
        else if(inRange(snum, 301, 500)) {
            sstyle = 'style="color:#5db5da"';
            stitle = '#5db5da';
        }
        else if(inRange(snum, 501, 800)) {
            sstyle = 'style="color:#4d3bd1"';
            stitle = '#4d3bd1';
        }
        else if(inRange(snum, 801, 1000)) {
            sstyle = 'style="color:#be1cc8"';
            stitle = '#be1cc8';
        }
        else if(inRange(snum, 1001, 10000000)) {
            sstyle = 'style="color:#bf002d"';
            stitle = '#bf002d';
        }
        else{
            sstyle = 'style="font-weight:bold"';
            spre = 'font-weight';
            stitle = '#bf002d';
        }
        if (whatTodo === undefined) {
            $(this).empty();
            $(this).append ('<span class="seederDiv" ' + sstyle + '>' + snum + '</span>');
        }else{
            var titleObj = $(this).closest('tr').find('.name a');
            //$(this).closest('tr').find('.name a').wrapInner('<span class="titleDiv" ' + sstyle + '></span>');
            $(this).closest('tr').find('.name a').css(spre, stitle);
        }
    });
}
function removeColour(whatTodo) {
    $('div[class = "icell seeders"]').each(function(){
        var sstyle = 'style="color:#71942c"';
        if (whatTodo === undefined) {
            $(this).find('.seederDiv').contents().unwrap();
        }else{
            //var titleOjb = $(this).closest('tr').find('.titleDiv').html();
            //$(this).closest('tr').find('.name a').empty();
            //$(this).closest('tr').find('.name a').wrapInner(titleOjb);
            $(this).closest('tr').find('.name a').css({"color": ""});
        }
    });
}
function squeezeTorrents(){
//Squeezer
  function guess_title(title, ntype) {
    var guessed = cleanName2(title, ntype);
    return guessed ? guessed : title;
  }

  function fix_odd_even() {
    var odd = true;
    var count = 0;
    var was_odd = false;

    $('.torrents tr').each(function () {
      var tr = $(this);
      if (tr.hasClass('squeezer')) {
        count = parseInt(tr.attr('data-count')) + 1;
        was_odd = odd;
      }
      tr.removeClass('odd even').addClass(odd ? 'odd' : 'even');
      odd = --count == 0 ? !was_odd : !odd;
    });
  }

    var elements = $('.torrents tr');

    elements.each(function() {
      var tr = $(this);
      this.category_type = tr.find('.iconLink').attr('data-ccid');
      this.guessed_title = guess_title(tr.find('.name a').text(), this.category_type);
      //console.log(this.guessed_title);
      this.guessed_title_lowercase = this.guessed_title.toLowerCase();
      this.seeds = parseInt(tr.find('.seeders').text());
      this.peers = parseInt(tr.find('.leechers').text());
      this.snatched = parseInt(tr.find('.snatched').text());
    });

    for (var x = 0; x < elements.length; ++x) {
      var el = elements[x];
      if (el.processed)
        continue;

      var found_elements = [$(el).attr('data-tid')];
      var peers = el.peers;
      var seeds = el.seeds;
      var snatched = el.snatched;

      for (var y = elements.length - 1; y > x; y--) {
        var other = elements[y];
        if (!other.processed && el.guessed_title_lowercase == other.guessed_title_lowercase) {
          $(el).after(other);
          other.processed = true;
          peers = Math.max(other.peers, peers);
          seeds = Math.max(other.seeds, seeds);
          snatched = Math.max(other.snatched, snatched);
          found_elements.push($(other).attr('data-tid'));
        }
      }

      if (found_elements.length > 1) {
        var row = '<tr class="squeezer" data-count="' + found_elements.length + '">'
          + '<td class="circle" style="font-size: 20px; line-height: 44px; text-align:center">'
          + found_elements.length + '</td>'
          + '<td class="td-name"><div class="name"><a href="javascript:">'
          + el.guessed_title + '</a></div></td>'
          + '<td class="td-quick-download"></td><td class="td-uploaded-time"></td><td class="td-comment"></td><td class="td-size"></td>'
          + '<td class="td-snatched">' + snatched + '</td>'
          + '<td class="td-seeders">' + seeds + '</td>'
          + '<td class="td-leechers">' + peers + '</td></tr>';

        var new_row = $(el).before(row).prev();
        //var ids = $(found_elements.join(','));
        // ids.hide();

        var selectors = found_elements.map(function (id) { return 'tr[data-tid="' + id + '"]'; });
        var ids = selectors.join(', ');
        $('.torrents').find(ids).hide();

        new_row.data('ids', ids);
        new_row.data('show', false);

        //$('.torrents').find(ids).find('.name a').each(function () {
        //  this.innerHTML = this.innerHTML.substr(el.guessed_title.length);
        //});

        $('.torrents').find(ids).find('.circle').css({position: 'relative', left: '20px' });
        $('.torrents').find(ids).find('div.name').prepend('<div style="float: left; width: 30px; height: 20px"></div>');
        $('.torrents').find(ids).find('div.info').prepend('<div style="float: left; width: 30px; height: 20px"></div>');

        //console.log($('.torrents').find(ids).find('.label-danger').length);
        var numItems = $('.torrents').find(ids).find('.label-danger').length;
        if (numItems > 0){
           new_row.find('.name').append('&nbsp;&nbsp;<span class="new label label-danger">new</span>');
        }

        new_row.click(function () {
          var show = $(this).data('show');
          var ids  = $(this).data('ids');
          show ? $('.torrents').find(ids).hide() : $('.torrents').find(ids).show()
          $(this).data('show', !show);
        });

        fix_odd_even();
      }
    }
//Squeezer
}
function showThumbs(){
    var tOut;
    $('.name').hover(function() {
        var tr = $(this);
        tOut = setTimeout(function(){
            var href = tr.find('a:first').attr('href');
            if (href !== undefined){
                var fullink = 'https://www.torrentleech.org' + href;
                $.ajax({
                    url: fullink,
                    success: function(data) {
                        src = $(".imdb_cover img", data).prop("src");
                        if (src !== undefined){
                            return overlib('<img height="150px" src=\''+src+'\' style=\'border:1px solid black\'>');
                        }else{
                            return overlib('<img height="100px" title ="" src=\'https://icon-library.com/images/no-photo-available-icon/no-photo-available-icon-21.jpg\' style=\'border:1px solid black\'>');
                            //return nd();
                        }
                    }
                });
            }
        },300);
    },function(){
        clearTimeout(tOut);
        return nd();
    });
}
function setupAdminLTE() {
    $("[data-controlsidebar]").on('click', function () {
       // console.log("tst");
      var slide = !AdminLTE.options.controlSidebarOptions.slide;
      AdminLTE.options.controlSidebarOptions.slide = slide;
      if (!slide)
        $('.control-sidebar').removeClass('control-sidebar-open');
    });

    $("[data-boldtitles='toggle']").on('click', function () {
      var fontWeight = $('.table-responsive .name').css('font-weight');
      if (fontWeight == 'normal' || fontWeight == '400') {
         $('.table-responsive .name').css("font-weight", "bold");
         store('boldtitles', "bold");
      } else {
         $('.table-responsive .name').css("font-weight", "normal");
         store('boldtitles', "normal");
      }
    });

    $("[data-boldseeders='toggle']").on('click', function () {
      var fontWeight = $('.table-responsive .seeders').css('font-weight');
      if (fontWeight == 'normal' || fontWeight == '400') {
         $('.table-responsive .seeders').css("font-weight", "bold");
         store('boldseeders', "bold");
      } else {
         $('.table-responsive .seeders').css("font-weight", "normal");
         store('boldseeders', "normal");
      }
    });

    $("[data-coloredtitles='toggle']").on('click', function () {
        if ($(this).prop('checked')===true){
            addColour('title');
            store('colortitles', 1);
        }
        else if($(this).prop("checked") === false){
            removeColour('title');
            store('colortitles', 0);
        }
    });

    $("[data-coloredseeders='toggle']").on('click', function () {
        if ($(this).prop('checked')===true){
            addColour();
            store('colorseeders', 1);
        }
        else if($(this).prop("checked") === false){
            removeColour();
            store('colorseeders', 0);
        }
    });

    $("[data-tightbox='toggle']").on('click', function () {
        if ($(this).prop('checked')===true){
            store('tighterbox', "small");
            document.location.reload();
        }
        else if($(this).prop("checked") === false){
            store('tighterbox', "wide");
            document.location.reload();
        }
    });

    $("[data-imdbdetails='toggle']").on('click', function () {
        if ($(this).prop('checked')===true){
            $('.table-responsive span[class="filter"]').show();
            $('.table-responsive i[class="fa fa-tag"]').prev().show();
            $('.table-responsive i[class="fa fa-tag"]').show();
            store('imdbdetails', "1");
            //document.location.reload();
        }
        else if($(this).prop("checked") === false){
           $('.table-responsive span[class="filter"]').hide();
           $('.table-responsive i[class="fa fa-tag"]').prev().hide();
           $('.table-responsive i[class="fa fa-tag"]').hide();
           store('imdbdetails', "0");
           //document.location.reload();
        }
    });

    $("[data-extrabuttons='toggle']").on('click', function () {
        if ($(this).prop('checked')===true){
            $('div[class = "enhanceWrapper"]').show();
            store('extrabuttons', "1");
        }
        else if($(this).prop("checked") === false){
           $('div[class = "enhanceWrapper"]').hide();
           store('extrabuttons', "0");
        }
    });

    $("[data-squezzer='toggle']").on('click', function () {
        if ($(this).prop('checked')===true){
            store('squezzer', "1");
            document.location.reload();
        }
        else if($(this).prop("checked") === false){
           store('squezzer', "0");
           document.location.reload();
        }
    });

    $("[data-showxxx='toggle']").on('click', function () {
        if ($(this).prop('checked')===true){
            // $('a[class = "xxx"]').show();
            $('.xxx').show();
            store('showxxx', "1");
        }
        else if($(this).prop("checked") === false){
           //$('a[class = "xxx"]').hide();
           $('.xxx').hide();
           store('showxxx', "0");
        }
    });

    $("[data-covers='toggle']").on('click', function () {
        if ($(this).prop('checked')===true){
            store('covers', "1");
            document.location.reload();
        }
        else if($(this).prop("checked") === false){
           store('covers', "0");
           document.location.reload();
        }
    });

    $('#highlighter').keyup(function() {
        var highlight_txt = document.getElementById("highlighter");
        store("highlight", highlight_txt.value);
    });

   $("#data-reset-cookies").on('click', function () {
     localStorage.clear();
     alert("Settings restored !");
     document.location.reload();
    });
}

//Hide movie row vars
var stored_films = JSON.parse(localStorage.getItem("HiddenFilms") || "[]");
var any_hidden_film_removed = false;

function hide_film(film){
    function guess_title(title, ntype) {
        var guessed = cleanName2(title, ntype);
        return guessed ? guessed : title;
      }

    var hideme = $('.torrent').filter(function () {
        var tr = $(this);
        this.category_type = tr.find('.iconLink').attr('data-ccid');
        this.guessed_title = guess_title(tr.find('.name a').text(), this.category_type);
        return $(this).find('.name a').attr('href') == film.link || this.guessed_title == film.title;
    });
    hideme.hide();
}

function hide_films(films) {
    if (films !== null) {
        for (var value of films) {
            console.log(value);
            hide_film(value);
        };
    }
}
//////////////

//blank the page
var css = ".highlight { background-color: yellow; color: black !important;} html { font-family: 'Open Sans', sans-serif; height: 100%; background-color: #f5f5f5; visibility:hidden; !important} .results .torrents .torrent .quick-download-img {width: 25px; height: 25px; line-height: 22px; top: 13px; position: relative;} .tl.navbar{z-index:  1050;} .control-sidebar form {background-color:transparent !important;} .control-sidebar{position:absolute;padding-top:120px;z-index:1010}@media (max-width: 768px){.control-sidebar{padding-top:130px}}";
var overwritecss = ".container { width : 100% !important;}";
function initApplication() {

    $('.paglink, .sortable, .category').click(function(e){
        (function(open) {
            XMLHttpRequest.prototype.open = function() {
                this.addEventListener("readystatechange", function() {
                    //console.log(this.readyState);
                    if(this.readyState == 0){
                        document.location.reload();
                    }
                }, false);
                open.apply(this, arguments);
            };
        })(XMLHttpRequest.prototype.open);
    });

    $(".navbar-menu").append ('<li class="waves-effect waves-ripple"><a class="top-menu" title="TorrentLeech V5 Enhancer" href="#" id="control-sidebar" data-toggle="control-sidebar"><i style="font-size:20px; margin-top: -6px; color: rgb(255, 216, 0); vertical-align: middle; margin-right: 1px; margin-left: 1px;" class="fa fa-gears"></i><span style="font-size: 13px; margin-right: 3px;"></span></a></li>');
    $("body").append ('<aside class="control-sidebar control-sidebar-dark"> <div class="tab-content"> <div class="tab-pane" id="control-sidebar-settings-tab" style="position:fixed;padding-right:10px;"> <form method="post"> <h3 class="control-sidebar-heading">TL Enhancer Settings</h3> <div class="form-group2"> <label class="control-sidebar-subheading"> Bold Titles <input type=\'checkbox\' data-boldtitles=\'toggle\' class=\'pull-right\' > </label> <p> The default TL stylesheet. Bold titles for torrent names. </p> </div> <div class="form-group2"> <label class="control-sidebar-subheading"> Bold Seeders <input type=\'checkbox\' data-boldseeders=\'toggle\' class=\'pull-right\' > </label> <p> The default TL stylesheet. Bold seeder values. </p> </div> <div class="form-group2"> <label class="control-sidebar-subheading"> Add Colour to Torrent Titles <input type=\'checkbox\' data-coloredtitles=\'toggle\' class=\'pull-right\' > </label> <p> The darker the colour, the more seeders available. </p> </div> <div class="form-group2"> <label class="control-sidebar-subheading"> Add Colour to Seeders Column <input type=\'checkbox\' data-coloredseeders=\'toggle\' class=\'pull-right\' > </label> <p> The darker the colour, the more seeders available. </p> </div> <div class="form-group2"> <label class="control-sidebar-subheading"> Expand container <input type=\'checkbox\' data-tightbox=\'toggle\' class=\'pull-right\'> </label> <p> Expand containter width to 100% (needs page refresh) </p> </div> <div class="form-group2"> <label class="control-sidebar-subheading"> Show details <input type=\'checkbox\' data-imdbdetails=\'toggle\' class=\'pull-right\'> </label> <p> Show/Hide imdb details.</p> </div> <div class="form-group2"><label class="control-sidebar-subheading"> Show Enhancer buttons <input type=\'checkbox\' data-extrabuttons=\'toggle\' class=\'pull-right\'> </label> <p> Show/Hide Enhancer buttons. </p> </div> <div class="form-group2"><label class="control-sidebar-subheading"> Squeezer <input type=\'checkbox\' data-squezzer=\'toggle\' class=\'pull-right\'> </label> <p> Squeeze movies/tvshows into groups. (needs page refresh)</p> </div> <div class="form-group2"><label class="control-sidebar-subheading"> Show XXX button <input type=\'checkbox\' data-showxxx=\'toggle\' class=\'pull-right\' > </label> <p> Show/Hide XXX button. </p> </div> <div class="form-group2"><label class="control-sidebar-subheading"> Show Thumbnails<input type=\'checkbox\' data-covers=\'toggle\' class=\'pull-right\' > </label> <p> Get Thumbnail on title hover (needs page refresh) </p> </div> <div class="form-group2"><label class="control-sidebar-subheading"> Word highlight <input type=\'text\' id="highlighter" value="" style="width:205px" placeholder="ex: Dead,Big Bang"> </label> <p> Highlight words separated by comma. (needs page refresh) </p> </div><h3 class="control-sidebar-heading"></h3> <div class="form-group2"> <label class="control-sidebar-subheading"> Restore default TL settings <a href="javascript:void(0)" id="data-reset-cookies" class="text-red pull-right"><i class="fa fa-trash-o"></i></a> </label> </div> </form> </div> </div> </aside> <div class="control-sidebar-bg"></div>');
    $(".tab-content > .tab-pane" ).show();

    $('div[class = "name"]').each(function(i){
        var cache_this = this;
        $raw_text = $(this).closest('td').prev().find('a').attr('data-ccid');
        var category_type = $raw_text;
        //console.log(category_type);
        var imdbscore = $(this).find('span:#imdbOnBrowse').html();
        if(category_type == 'movies' || category_type == 'tv'){
            //console.log(imdbscore);
            if (imdbscore !== null && (imdbscore.indexOf('.')!=-1) ) {
                var remakeImdb = imdbscore.replace(" &nbsp;&nbsp; ", ""); //remove that extra space
                var score = remakeImdb.split(" ");
                var str1 = score[0];
                if (str1.indexOf(".")!=-1) {
                    $(cache_this).find('div.name').append(' <span style="color:yellow">('+str1+')</span>');
                    $(cache_this).find('span:#imdbOnBrowse').html(function(index,html){
                        return html.replace('&nbsp;&nbsp; '+str1+' ','');
                    });
                } else {
                    $(cache_this).find('div.name').append(' <span style="color:red">(N/A)</span>');
                }
            }
            $(this).append($('<div>').addClass('enhanceWrapper')
                           .css({float:'right', margin: '14px 5px 0 0'})
                           .data('category', category_type));
        }
        //Hide row button
        $(this).append('<span title="Hide torrent" class=\'myhide\' style=\'cursor: pointer; margin-left: 10px; font-size: 14px;\'><i class="fa fa-eye-slash" aria-hidden="true">&nbsp;&nbsp;</i></span>');
    });
    $.each(buttons_collection,function(index, value) {
        $('.enhanceWrapper').append($('<img />')
                                    .addClass('enhance-buttons_collection')
                                    .attr({src: value.src,
                                           alt: value.rollover,
                                           title: value.type})
                                    .css({margin: "0 8px 0 0",
                                          cursor: 'pointer',
                                          float: 'left'})
                                    .data('name',value.type));
    });
    $('img[class="enhance-buttons_collection"]').load(function(){
        $name = $(this).closest('td').find('a').text();
        var cat_type = $(this).parent().data('category');

        switch($(this).data('name')){
            case 'traktv':
                if(cat_type == 'games'){
                    $(this).remove();
                }
                break;
            case 'trailer':
                if(cat_type == 'tv'){
                    $(this).remove();
                }
                break;
            case 'info':
                if(cat_type == 'movies'){
                    $(this).remove();
                }
                break;
        }
    });
    $('img[class="enhance-buttons_collection"]').hover(function(){
        $src = $(this).attr('src');
        $alt = $(this).attr('alt');
        $(this).attr('src', $alt);
        $(this).attr('alt', $src);
    },
    function(){
        $src = $(this).attr('src');
        $alt = $(this).attr('alt');
        $(this).stop(false,true).attr('src', $alt);
        $(this).stop(false,true).attr('alt', $src);
    });
    $('img[class="enhance-buttons_collection"]').click(function(){
        //$(this).stop(true,true).effect("bounce", { times:3 }, 300);

        //diable the add to bookmark feature if clicking the enhance buttons
        $(this).parents('tbody tr').addClass('row_selected');

        //$raw_text = $(this).closest('td').prev().find('a').attr('href');
        $name = $(this).closest('td').find('a').text();
        //var cat_type = $(this).parent().data('category');
        var cat_type = $(this).closest('tr').children('td:first').find('a').attr('data-ccid');
        //console.log(cat_type);

        switch($(this).data('name')){
            case 'copy':
                window.prompt ("Copy to clipboard: Ctrl+C, Enter", $name);
                break;
            case 'info':
                if(cat_type == 'movies'){
                    openImdb($name, cat_type);
                }
                else if(cat_type == 'tv')
                    openTv($name, cat_type);
                else if(cat_type == 'games')
                    openGameReview($name, cat_type);
                break;
            case 'traktv':
                if(cat_type != 'games'){
                    opentraktTV($name, cat_type);
                }else{
                    $(this).remove();
                }
                break;
            case 'trailer':
                if(cat_type == 'games')
                    openGamePlay($name, cat_type);
                else if(cat_type == 'movies')
                    openTrailer($name, cat_type);
                break;
            case 'episodes':
                if(cat_type == 'tv')
                    openEpisodes($name, cat_type);
                break;
        }
    });

    //Hide row
    $('body').append('<span class="view_list" style="float:right; cursor: pointer; margin-right: 10px; font-size: 14px; border: 1px solid #333; padding: 5px 8px; border-radius: 4px;">View Hidden Films </span>');
    $('.view_list').click(function(){
        $('body').append('<div id="hidden_list_bg" style="position: fixed; top: 0; left: 0; right: 0; bottom: 0; background: rgba(0,0,0,0.4);"></div><div id="hidden_list_wrapper" style="position: fixed; width: 450px; height: 600px; padding: 10px; top: 50%; left: 50%; margin-top: -300px; margin-left: -200px; background: #FFF; border-radius: 4px;"></div>');
        $('#hidden_list_wrapper').append('<div id="close_hidden_list" style="color: #000; font-weight: 700; font-size: 22px; display: inline-block; position: absolute; top: 6px; right: 9px; cursor:pointer;">&times;</div>');
        $('#hidden_list_wrapper').append('<div id="clear_list" style="position: absolute; left: 8px; top: 8px; font-size: 12px; color: #666; border: 1px solid #666; padding: 5px 8px; border-radius: 4px; cursor: pointer;">Clear All Hidden Films</div>');
        $('#hidden_list_wrapper').append('<div id="hidden_list" style="height: 550px; margin-top: 35px; overflow-y: scroll;"></div>');
        $('#hidden_list').append('<table id="hidden_list_table" style="width: 100%"></table>');
        stored_films.forEach(function(item) {
            $('#hidden_list_table').append('<tr><td style="color: #666; font-size: 14px;">'+item.title+'</td><td style="text-align: right;"><div class="remove_hidden_film" data-id="'+item.id+'" style="color: red; font-weight: 700; font-size: 18px; cursor: pointer">&times;</div></td></tr>');
        });

    });

    $('body').on('click', '#close_hidden_list', function(){
        $('#hidden_list_wrapper, #hidden_list_bg').remove();
        if(any_hidden_film_removed) {
            location.reload();
        }
    });

    $('body').on('click', '.remove_hidden_film', function(){
        var id = +$(this).attr('data-id');
        //console.log('removing',id);
        stored_films.map(function(o) { return o.id; });
        stored_films.splice(stored_films.map(function(o) { return o.id; }).indexOf(id),1);
        $(this).closest('tr').remove();
        store('HiddenFilms', JSON.stringify(stored_films));
        any_hidden_film_removed = true;
    });

    $('body').on('click', '#clear_list', function(){
        store('HiddenFilms', JSON.stringify([]));
        location.reload();
    });
    $('.myhide').click(function () {
        var fulltitle = $(this).closest('td').find('a').text();
        var cat_type = $(this).closest('tr').children('td:first').find('a').attr('data-ccid');
        var title = cleanName2(fulltitle, cat_type);
        var $infolink = $(this).closest('td').find('a');

        var hide_this = {
            id: +new Date,
            title: title,
            link: $infolink.attr('href')
        }
        if (hide_this !== undefined) {
            var found = jQuery.inArray(hide_this, stored_films);
            if (found < 0) {
                stored_films.push(hide_this);
            }
            localStorage.setItem("HiddenFilms", JSON.stringify(stored_films));
            hide_film(hide_this);
        }
    });
    /////

    $('.results').append('<div class="text-center"><a href="#" id="download-all">Download All</a></div>');
    $('#download-all').on('click', function (event) {
        event.preventDefault();
        $('.download').multiDownload({delay: 500});
    });

    // This is the equivalent of @run-at document-end
    var titleSettings = get('boldtitles');
    var seederSettings = get('boldseeders');
    //console.log(seederSettings);
    var colorTitSettings = get('colortitles');
    var colorSeedSettings = get('colorseeders');
    var tighterSettings = get('tighterbox');
    var imdbdetails = get('imdbdetails');
    var extrabuttons = get('extrabuttons');
    var showxxxbutton = get('showxxx');
    var dosqueezer = get('squezzer');
    var highlightwords = get('highlight');
    var previewcovers = get('covers');

    if (dosqueezer !== null && dosqueezer === "1") {
        squeezeTorrents();
        $("[data-squezzer='toggle']").prop('checked', true);
    }else{
        $("[data-squezzer='toggle']").prop('checked', false);
    }
    //torrent titles
    if (titleSettings === "normal") {
        $("[data-boldtitles='toggle']").prop('checked', false);
    }else{
        $("[data-boldtitles='toggle']").prop('checked', true);
    }
    if (titleSettings !== null)
        $('.table-responsive .name').css("font-weight", titleSettings);
    //torrent seeders
    if (seederSettings === "normal") {
        $("[data-boldseeders='toggle']").prop('checked', false);
    }else{
        $("[data-boldseeders='toggle']").prop('checked', true);
    }
    if (seederSettings !== null)
        $('.table-responsive .seeders').css("font-weight", seederSettings);
    //color
    if (colorTitSettings !== null && colorTitSettings === "1") {
        addColour('title');
        $("[data-coloredtitles='toggle']").prop('checked', true);
    }else{
        $("[data-coloredtitles='toggle']").prop('checked', false);
    }
    if (colorSeedSettings !== null && colorSeedSettings === "1") {
        addColour();
        $("[data-coloredseeders='toggle']").prop('checked', true);
    }else{
        $("[data-coloredseeders='toggle']").prop('checked', false);
    }
    //details
    if (imdbdetails !== null && imdbdetails === "0") {
        $('.table-responsive span[class="filter"]').hide();
        $('.table-responsive i[class="fa fa-tag"]').prev().hide();
        $('.table-responsive i[class="fa fa-tag"]').hide();
        $("[data-imdbdetails='toggle']").prop('checked', false);
    }else{
        $("[data-imdbdetails='toggle']").prop('checked', true);
    }
    //enhancer buttons
    if (extrabuttons !== null && extrabuttons === "0") {
        $('div[class="enhanceWrapper"]').hide();
        $("[data-extrabuttons='toggle']").prop('checked', false);
    }else{
        $("[data-extrabuttons='toggle']").prop('checked', true);
    }
    //container
    if (tighterSettings !== null && tighterSettings === "small") {
        addStyle(overwritecss);
        $("[data-tightbox='toggle']").prop('checked', true);
    }else{
        $("[data-tightbox='toggle']").prop('checked', false);
    }
    //xxx
    if (showxxxbutton !== null && showxxxbutton === "0") {
        //$('div[class="categories"]').find(('a.xxx')).hide();
        $('.xxx').hide();
        $("[data-showxxx='toggle']").prop('checked', false);
    }else{
        $('.xxx').show();
        $("[data-showxxx='toggle']").prop('checked', true);
    }

    if (highlightwords !== null && highlightwords != "") {
       $('#highlighter').val(highlightwords);
       var array = highlightwords.split(",");
       $('.torrents').highlight(array, { element: 'span', className: 'highlight' });
   }

    if (previewcovers !==null && previewcovers === "1"){
      showThumbs();
      $("[data-covers='toggle']").prop('checked', true);
    }else{
      $("[data-showxxx='toggle']").prop('checked', false);
    }

    hide_films(stored_films);
	//done modifying document, now show it
	document.documentElement.style.visibility="visible";
    //initi slider settings
    setupAdminLTE();
    $.AdminLTE.controlSidebar.activate();
}

loadDone = false;
var waitForPageLoad = function() {
	var $pageloaded = $('.pace-progress').attr('data-progress');
	if($pageloaded >= 99){
		loadDone = true;
	}
	if (loadDone) {
        initApplication();
        loadDone = false;
	} else {
       //console.log($pageloaded);
	   setTimeout(waitForPageLoad, 500);
	}
};
window.addEventListener("DOMContentLoaded", waitForPageLoad, false);


(function applyCSS() {
	var h = document.getElementsByTagName("html");
	if (h && h[0]) {
		addStyle(css);
	} else {
		setTimeout(applyCSS, 50);
	}
})();

/*
 * jQuery Highlight plugin
 *
 * Based on highlight v3 by Johann Burkard
 * http://johannburkard.de/blog/programming/javascript/highlight-javascript-text-higlighting-jquery-plugin.html
 *
 * Code a little bit refactored and cleaned (in my humble opinion).
 * Most important changes:
 *  - has an option to highlight only entire words (wordsOnly - false by default),
 *  - has an option to be case sensitive (caseSensitive - false by default)
 *  - highlight element tag and class names can be specified in options
 *
 * Usage:
 *   // wrap every occurrance of text 'lorem' in content
 *   // with <span class='highlight'> (default options)
 *   $('.torrents').highlight('lorem');
 *
 *   // search for and highlight more terms at once
 *   // so you can save some time on traversing DOM
 *   $('.torrents').highlight(['lorem', 'ipsum']);
 *   $('#content').highlight('lorem ipsum');
 *
 *   // search only for entire word 'lorem'
 *   $('#content').highlight('lorem', { wordsOnly: true });
 *
 *   // don't ignore case during search of term 'lorem'
 *   $('#content').highlight('lorem', { caseSensitive: true });
 *
 *   // wrap every occurrance of term 'ipsum' in content
 *   // with <em class='important'>
 *   $('#content').highlight('ipsum', { element: 'em', className: 'important' });
 *
 *   // remove default highlight
 *   $('#content').unhighlight();
 *
 *   // remove custom highlight
 *   $('#content').unhighlight({ element: 'em', className: 'important' });
 *
 *
 * Copyright (c) 2009 Bartek Szopka
 *
 * Licensed under MIT license.
 *
 */

jQuery.extend({
    highlight: function (node, re, nodeName, className) {
        if (node.nodeType === 3) {
            var match = node.data.match(re);
            if (match) {
                var highlight = document.createElement(nodeName || 'span');
                highlight.className = className || 'highlight';
                var wordNode = node.splitText(match.index);
                wordNode.splitText(match[0].length);
                var wordClone = wordNode.cloneNode(true);
                highlight.appendChild(wordClone);
                wordNode.parentNode.replaceChild(highlight, wordNode);
                return 1; //skip added node in parent
            }
        } else if ((node.nodeType === 1 && node.childNodes) && // only element nodes that have children
                !/(script|style)/i.test(node.tagName) && // ignore script and style nodes
                !(node.tagName === nodeName.toUpperCase() && node.className === className)) { // skip if already highlighted
            for (var i = 0; i < node.childNodes.length; i++) {
                i += jQuery.highlight(node.childNodes[i], re, nodeName, className);
            }
        }
        return 0;
    }
});

jQuery.fn.unhighlight = function (options) {
    var settings = { className: 'highlight', element: 'span' };
    jQuery.extend(settings, options);

    return this.find(settings.element + "." + settings.className).each(function () {
        var parent = this.parentNode;
        parent.replaceChild(this.firstChild, this);
        parent.normalize();
    }).end();
};

jQuery.fn.highlight = function (words, options) {
    var settings = { className: 'highlight', element: 'span', caseSensitive: false, wordsOnly: false };
    jQuery.extend(settings, options);

    if (words.constructor === String) {
        words = [words];
    }
    words = jQuery.grep(words, function(word, i){
      return word != '';
    });
    words = jQuery.map(words, function(word, i) {
      return word.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
    });
    if (words.length == 0) { return this; };

    var flag = settings.caseSensitive ? "" : "i";
    var pattern = "(" + words.join("|") + ")";
    if (settings.wordsOnly) {
        pattern = "\\b" + pattern + "\\b";
    }
    var re = new RegExp(pattern, flag);

    return this.each(function () {
        jQuery.highlight(this, re, settings.element, settings.className);
    });
};