KissAnimeList

Integrates MyAnimeList into diverse sites, with auto episode tracking.

As of 2017-05-18. See the latest version.

// ==UserScript==
// @name        KissAnimeList
// @version     0.83
// @description Integrates MyAnimeList into diverse sites, with auto episode tracking.
// @author      [email protected]
// @license     Creative Commons; http://creativecommons.org/licenses/by/4.0/
// @include     /https?://kissanime.ru/Anime/*/
// @include     /https?://kissanime.to/Anime/*/
// @include     /https?://kissanime.ru/BookmarkList
// @include     /https?://kissanime.to/BookmarkList
// @exclude     /https?://kissanime.ru/AnimeList*
// 
// @include     /https?://kissmanga.com/manga/*/
// @include     /https?://kissmanga.com/BookmarkList
// @exclude     /https?://kissmanga.com/MangaList*
// 
// @include     /https?://myanimelist.net/anime/*
// @include     /https?://myanimelist.net/anime/*/
// @include     /https?://myanimelist.net/manga/*
// @include     /https?://myanimelist.net/manga/*/
// 
// @include     /https?://www.masterani.me/anime/info/*/
// @include     /https?://www.masterani.me/anime/watch/*/
// 
// @require     http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js
// @connect     www.google.com
// @connect     ipv4.google.com
// @connect     myanimelist.net
// @connect     kissanimelist.firebaseio.com
// @connect     *
// @grant       GM_xmlhttpRequest
// @grant       GM_getValue
// @grant       GM_setValue
// @grant       GM_listValues
// @grant       GM_deleteValue
// @grant       GM_addStyle
// @run-at      document-start
// @namespace https://greasyfork.dpdns.org/users/92233
// ==/UserScript==

(function() {
    'use strict';
    if (window.top != window.self) {return; }
    var googleover = 0;

    var con = console;
    con = {
        log: function() {},
        error: function() {},
        debug: function() {}
    };

    var element = new Image();
    Object.defineProperty(element, 'id', {
      get: function () {
        con = console;
      }
    });
    console.log('%cKissMangaList', element);

    var malBookmarks = GM_getValue( 'malBookmarks', 1 );
    var classicBookmarks = GM_getValue( 'classicBookmarks', 0 );
    if(classicBookmarks === 0){
        var BookmarksStyle = 1;
    }

    if( window.location.href.indexOf("kissanime.ru") > -1 ){
        //#########Kissanime#########
        var domain = 'http://kissanime.ru';
        var textColor = '#d5f406';
        var dbSelector = 'Kissanime';
        var listType = 'anime';
        var bookmarkCss = ".listing tr td:nth-child(1){height: 150px;padding-left: 125px;} .listing tr td{vertical-align: top;}";
        var bookmarkFixCss = ".bigBarContainer {margin: 0px; width: 630px !important; text-align: left; float: left;}";

        $.fn.imageCache = function() {
            return $('#rightside').find('img').attr('src');
        };

        $.isOverviewPage = function() {
            if(typeof window.location.href.split('/')[5] != 'undefined'){
                if($('#centerDivVideo').length){
                    return false;
                }
            }
            return true;
        };
        $.episodeListSelector = function() {
            return $(".listing a");
        };
        $.fn.episodeListElementHref = function() {
            return $.absoluteLink(this.attr('href'));
        };
        $.fn.episodeListElementTitle = function() {
            return this.text().replace($('.bigChar').text(),'');
        };
        $.fn.episodeListNextElement = function() {
            return this.parent().parent().prev().find('a');
        };
        $.handleNextLink = function(truelink, anime){
            return truelink;
        };

        $.urlEpisodePart = function(url) {
            return url.split("/")[5].split("?")[0];
        };
        $.urlAnimeIdent = function(url) {
            return url.split('/').slice(0,5).join('/');
        };
        $.urlAnimeTitle = function(url) {
            return url.split("/")[4];
        };

        $.EpisodePartToEpisode = function(string) {
            var temp = [];
            temp = string.match(/[e,E][p,P][i,I]?[s,S]?[o,O]?[d,D]?[e,E]?\D?\d{3}/);
            if(temp !== null){
                string = temp[0];
            }
            temp = string.match(/\d{3}/);
            if(temp === null){
                string = 0;
            }else{
                string = temp[0];
            }
            return string;
        };

        $.fn.uiPos = function() {
            this.insertAfter($(".bigChar").first());
        };
        $.fn.uiWrongPos = function() {
            this.insertAfter($(".bigChar").first());
        };
        $.fn.uiHeadPos = function() {
            this.appendTo($(".barTitle").first());
        };

        $.docReady = function(data) {
            return $( document).ready(data);
        };

        $.normalUrl = function(){
            return $.urlAnimeIdent(window.location.href);
        };

        $.bookmarkEntrySelector = function() {
            return $(".trAnime");
        };

        $.fn.classicBookmarkButton = function(checkClassic) {
            this.before('<div><input type="checkbox" id="classicBookmarks" '+checkClassic+' > Classic styling</div><div class="clear2">&nbsp;</div>');
        };
        $.fn.bookmarkButton = function(check) {
            this.before('<div><input type="checkbox" id="malBookmarks" '+check+' > MyAnimeList Bookmarks</div><div class="clear2">&nbsp;</div>');
        };

        $.BookmarksStyleAfterLoad = function() {
            if( BookmarksStyle == 1 ){
                var optionsTarget = $("#optionsTarget");
                var blackSpacer = "";
            }else{
                var optionsTarget = $("#divIsShared");
                var blackSpacer = '<th id="endSpacer" width="36%" style="border: 0;">';
            }
            $(".head").html('<th id="cssTableSet" style="min-width:120px;padding-right: 5px;"></th><th></th>'+blackSpacer+'</th>');
            $( ".listing tr td:nth-child(1)" ).before("<td class='Timage' style='padding-left: 0;'></td>");
            $( ".listing tr td:nth-child(1)" ).css("height","150px");
            optionsTarget.after('<div class="clear2">&nbsp;</div><div><button type="button" id="clearCache">Clear Cache</button></div>');
            $("#clearCache").click( function(){
                clearCache();
            });   
        };
        //###########################
    }else if( window.location.href.indexOf("kissmanga.com") > -1 ){
        //#########Kissmanga#########
        var domain = 'http://kissmanga.com';
        var textColor = '#72cefe';
        var dbSelector = 'Kissmanga';
        var listType = 'manga';
        var bookmarkCss = ".listing tr td:nth-child(1){height: 150px;padding-left: 125px;} .listing tr td{vertical-align: top;}";
        if(classicBookmarks == 0){
            bookmarkCss += '#leftside{width: 581px !important;} #rightside{ float: left !important; margin-left: 30px;}';
        }
        var bookmarkFixCss = "";
        BookmarksStyle =


        $.fn.imageCache = function() {
            return $('#rightside').find('img').attr('src');
        };

        $.isOverviewPage = function() {
            if($("#malp").width() !== null){
                return true;
            }else{
                return false;
            }
        };
        $.episodeListSelector = function() {
            return $(".listing a");
        };
        $.fn.episodeListElementHref = function() {
            return $.absoluteLink(this.attr('href'));
        };
        $.fn.episodeListElementTitle = function() {
            return this.text().replace($('.bigChar').text(),'');
        };
        $.fn.episodeListNextElement = function() {
            return this.parent().parent().prev().find('a');
        };
        $.handleNextLink = function(truelink, anime){
            return truelink;
        };

        $.urlEpisodePart = function(url) {
            return url.split("/")[5].split("?")[0];
        };
        $.urlAnimeIdent = function(url) {
            return url.split('/').slice(0,5).join('/');
        };
        $.urlAnimeTitle = function(url) {
            return url.split("/")[4];
        };

        $.EpisodePartToEpisode = function(string) {
            var temp = [];
            try{
                string = string.replace($('.bigChar').attr('href').split('/')[2],'');
            }catch(e){string = string.replace(window.location.href.split("/")[4],'');}
            temp = string.match(/[c,C][h,H][a,A]?[p,P]?[t,T]?[e,E]?[r,R]?\D?\d+/);
            if(temp === null){
                string = string.replace(/[V,v][o,O][l,L]\D?\d+/,'');
                temp = string.match(/\d{3}/);
                if(temp === null){
                    temp = string.match(/\d+/);
                    if(temp === null){
                        string = 0;
                    }else{
                        string = temp[0];
                    }
                }else{
                    string = temp[0];
                }
            }else{
                string = temp[0].match(/\d+/)[0];
            }
            return string;
        };

        $.fn.uiPos = function() {
            this.insertAfter($(".bigChar").first());
        };
        $.fn.uiWrongPos = function() {
            this.insertAfter($(".bigChar").first());
        };
        $.fn.uiHeadPos = function() {
            this.appendTo($(".barTitle").first());
        };

        $.docReady = function(data) {
            return $( document).ready(data);
        };

        $.normalUrl = function(){
            return $.urlAnimeIdent(window.location.href);
        };

        $.bookmarkEntrySelector = function() {
            return $(".listing tr:not(.head)");
        };

        $.fn.classicBookmarkButton = function(checkClassic) {
            $("#rightside .barContent div").last().after('<div><input type="checkbox" id="classicBookmarks" '+checkClassic+' > Classic styling</div><div class="clear2">&nbsp;</div>');
        };
        $.fn.bookmarkButton = function(check) {
            $("#rightside .barContent div").last().after('<div class="clear2" style="border-bottom: 1px solid #DDD2A4;">&nbsp;</div><div class="clear2">&nbsp;</div><div><input type="checkbox" id="malBookmarks" '+check+' > MyAnimeList Bookmarks</div>');
        };

        $.BookmarksStyleAfterLoad = function() {
            $(".head").html('<th id="cssTableSet" style="min-width:120px;padding-right: 5px;"></th><th></th>');//<th width="21%" style=""></th>');
            $( ".listing tr td:nth-child(1)" ).before("<td class='Timage' style='padding-left: 0;'></td>");
            $( ".listing tr td:nth-child(1)" ).css("height","150px");
            $("#rightside .barContent div").last().after('<div class="clear2">&nbsp;</div><div><button type="button" id="clearCache">Clear Cache</button></div>');
            $("#clearCache").click( function(){
                clearCache();
            }); 
        };
        //###########################
    }else{
        //#########Masterani.me#########
        var domain = 'https://www.masterani.me';
        var textColor = 'white';
        var dbSelector = 'Masterani';
        var listType = 'anime';
        var bookmarkCss = "";
        var bookmarkFixCss = "";
        var winLoad = 0;

        $.fn.imageCache = function() {
            return $('.class').first().find('img').attr('src');
        };

        $.isOverviewPage = function() {
            if($.normalUrl().split('/')[4] !== 'watch'){
                return true;
            }else{
                return false;
            }
        };
        $.episodeListSelector = function() {
            return $(".thumbnail a");
        };
        $.fn.episodeListElementHref = function() {
            return $.absoluteLink(this.attr('href'));
        };
        $.fn.episodeListElementTitle = function() {
            return this.find("div").text()+' ('+this.find("span").text()+')';
        };
        $.fn.episodeListNextElement = function() {
            return this.parent().parent().parent().next('.thumbnail').find('a');
        };
        $.handleNextLink = function(truelink, anime){
            $('.menu.pagination').off('click').on( "click", function() {
                handleanime(anime);
            });
            if(truelink == null){
                var nextEp = parseInt(anime['.add_anime[num_watched_episodes]'])+1;
                if(nextEp <= parseInt(anime['totalEp'])){
                    return '<a style="color: white;" href="/anime/watch/'+$.normalUrl().replace(/#[^#]*$/, "").replace(/\?[^\?]*$/, "").split("/")[5]+'/'+nextEp+'">Ep. '+nextEp+'</a>';
                }
            }
            return truelink;
        };

        $.urlEpisodePart = function(url) {
            return url.split("/")[6].split("?")[0];
        };
        $.urlAnimeIdent = function(url) {
            return url.split('/').slice(0,6).join('/');
        };
        $.urlAnimeTitle = function(url) {
            return url.split("/")[5].replace(/^\d+[-]?/, '');
        };

        $.EpisodePartToEpisode = function(string) {
            return string;
        };

        $.fn.uiPos = function() {
            this.prependTo($("#stats").first());
        };
        $.fn.uiWrongPos = function() {
            this.appendTo($(".ui.info.list").first());
        };
        $.fn.uiHeadPos = function() {
            this.appendTo($("h1").first());
        };

        $(window).load(function(){
            winLoad = 1;
        });
        if(window.location.href.indexOf("/info/") > -1){
            $.docReady = function(data) {
                var checkExist = setInterval(function() {
                    if ($('#stats').length) {
                        clearInterval(checkExist);
                        if(winLoad == 0){
                            //winLoad = 1;alert();
                            return $(window).load(data);
                        }else{
                            return $( document).ready(data);
                        }
                    }
                }, 500);
            };
        }else{
            $.docReady = function(data) {
                return $( document).ready(data);
            }
        };

        $.normalUrl = function(){
            return $.urlAnimeIdent(window.location.href);
        };

        $.bookmarkEntrySelector = function() {
            return $(".trAnime");
        };

        $.fn.classicBookmarkButton = function(checkfix) {
        };
        $.fn.bookmarkButton = function(check) {
        };

        $.BookmarksStyleAfterLoad = function() {
        };
        //###########################
    }
    //#######Anime or Manga######
    if(listType == 'anime'){
        var googleMalUrl = "site:myanimelist.net/Anime/+-site:myanimelist.net/Anime/genre/+-site:myanimelist.net/anime/season/+";
        var middleType = 'episodes';
        var middleVerb = 'watched';
    }else{
        var googleMalUrl = "site:myanimelist.net/manga/+-site:myanimelist.net/manga/genre/+-site:myanimelist.net/manga/season/+";
        var middleType = 'chapters';
        var middleVerb = 'read';
    }
    //###########################
    
    $.absoluteLink = function(url) {
        if (typeof url === "undefined") {
            return url;
        }
        if(!url.startsWith("http")) { url = domain + url;}
        return url;
    };
    $.titleToDbKey = function(title) {
        return title.toLowerCase().replace('#', '');
    };

    //ignore loading
    if(document.title == "Please wait 5 seconds..."){
        con.log("loading");
        return;
    }

    function handleanime(anime){
        if(GM_getValue( dbSelector+'/'+$.titleToDbKey($.urlAnimeTitle($.urlAnimeIdent($.normalUrl())))+'/image' , null) == null ){
            try{
                GM_setValue( dbSelector+'/'+$.titleToDbKey($.urlAnimeTitle($.urlAnimeIdent($.normalUrl())))+'/image', $().imageCache() );
            }catch(e){}
        }
        if(anime['login'] === 0){
            $('#MalLogin').css("display","none");
            $("#MalData").css("display","initial");
            $("#MalInfo").text("");
            $("#malRating").attr("href", anime['malurl']).text("Loading");
            $("#malRating").after("&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Please log in on <a href='https://myanimelist.net/login.php'>MyAnimeList!<a>");
            getcommondata(anime['malurl']);
            return;
        }
        if($.isOverviewPage()){
            $("#flash").attr("anime", anime['.'+listType+'_id']);
            $("#malRating").attr("href", anime['malurl']).text("Loading");
            $("#malStatus").val(anime['.add_'+listType+'[status]']);
            $("#malEpisodes").val(anime['.add_anime[num_watched_episodes]']);
            $("#malTotal").text(anime['totalEp']); 
            if(anime['totalEp'] == 0){
               $("#malTotal").text('?'); 
            }
            $("#malUserRating").val(anime['.add_'+listType+'[score]']);

            //####Manga####
            $("#malVolumes").val(anime['.add_manga[num_read_volumes]']);
            $("#malChapters").val(anime['.add_manga[num_read_chapters]']);
            $("#malTotalVol").text(anime['totalVol']); 
            if(anime['totalVol'] == 0){
               $("#malTotalVol").text('?'); 
            }
            $("#malTotalCha").text(anime['totalChap']); 
            if(anime['totalChap'] == 0){
               $("#malTotalCha").text('?'); 
            }
            //#############

            $("#MalData").css("display","initial");
            $("#MalInfo").text("");

            $( "#malEpisodes" ).change(function() {
                updatebutton();
            });
            //####Manga####
            $( "#malVolumes" ).change(function() {
                updatebutton();
            });
            $( "#malChapters" ).change(function() {
                updatebutton();
            });
            //#############
            $( "#malUserRating" ).change(function() {
                updatebutton();
            });
            $( "#malStatus" ).change(function() {
                updatebutton();
            });

            getcommondata(anime['malurl']);

            var episodelink;
            var linkbackup = null;
            var truelink = null;
            $('.lastOpen').remove();
            $.episodeListSelector().each(function( index ) {
                if(listType == 'anime'){
                    if(con == console){
                        $(this).after('  Episode: '+urlToEpisode($(this).episodeListElementHref()));
                    }
                    try{
                        episodelink = urlToEpisode($(this).episodeListElementHref());
                    }catch(e) {
                        episodelink = 1;
                    }
                    $(this).parent().parent().css("background-color","initial");
                    if(episodelink == parseInt(anime['.add_anime[num_watched_episodes]'])){
                        $(this).parent().parent().css("background-color","#002966");
                        if(typeof $(this).episodeListNextElement().episodeListElementHref() !== "undefined"){
                            truelink = '<a style="color: white;" href="'+$(this).episodeListNextElement().episodeListElementHref()+'">'+$(this).episodeListNextElement().episodeListElementTitle()+'</a>';
                        }
                    }
                }else{
                    if(con == console){
                        $(this).after('   Chapter: '+urlToChapter($(this).episodeListElementHref()));
                        $(this).after('Volume: '+urlToVolume($(this).episodeListElementHref()));
                    }
                    episodelink = urlToChapter($(this).episodeListElementHref());
                    $(this).parent().parent().css("background-color","initial");
                    if($(this).attr('href') == commentToUrl(anime['.add_manga[comments]'])){
                        $(this).parent().parent().css("background-color","#861515");
                        linkbackup = '<a style="color: red;" href="'+$(this).episodeListNextElement().episodeListElementHref()+'">'+$(this).episodeListNextElement().episodeListElementTitle()+'</a>';
                        $(this).prepend('<span class="lastOpen">[Last opened]</span>');
                    }
                    if(episodelink == parseInt(anime['.add_manga[num_read_chapters]']) && parseInt(anime['.add_manga[num_read_chapters]']) != 0){
                        $(this).parent().parent().css("background-color","#002966");
                        truelink = '<a style="color: white;" href="'+$(this).episodeListNextElement().episodeListElementHref()+'">'+$(this).episodeListNextElement().episodeListElementTitle()+'</a>';
                    }
                }
            });
            truelink = $.handleNextLink(truelink, anime);
            if(listType == 'anime'){
                $(".headui").html(truelink);
            }else{
                if(truelink == null){
                    if(linkbackup != null){
                        $(".headui").html(linkbackup);
                    }
                }else{
                    $(".headui").html(truelink);
                }
            }
        }else{
            if(listType == 'anime'){
                //update
                try{
                    var curEpisode = urlToEpisode(window.location.href);
                }catch(e) {
                    var curEpisode = 1;
                }
                //if(curEpisode > anime['.add_anime[num_watched_episodes]']){
                var animechange = {};
                animechange['.add_anime[num_watched_episodes]'] = curEpisode;
                animechange['checkIncrease'] = 1;
                setanime( $.normalUrl(),animechange);
            }else{
                //update
                var curChapter = urlToChapter(window.location.href);
                var curVolume = urlToVolume(window.location.href);
                //if(curChapter > anime['.add_manga[num_read_volumes]']){
                var animechange = {};
                animechange['.add_manga[num_read_chapters]'] = curChapter;
                animechange['.add_manga[num_read_volumes]'] = curVolume;
                animechange['.add_manga[comments]'] = handleComment(window.location.href, anime['.add_manga[comments]']);
                animechange['checkIncrease'] = 1;
                setanime( $.normalUrl(),animechange);
            }
        }
    }

    function urlToEpisode(url){
        var string = $.urlEpisodePart(url);
        string = $.EpisodePartToEpisode(string);
        var Offset = GM_getValue(dbSelector+'/'+$.titleToDbKey($.urlAnimeTitle($.urlAnimeIdent(url)))+'/Offset' , null);
        if( Offset != null){
            string = parseInt(string)+parseInt(Offset);
        }
        return parseInt(string);
    }

    function urlToChapter(url){
        return urlToEpisode(url);
    }

    function urlToVolume(string){
        try{
            string = string.match(/[V,v][o,O][l,L]\D?\d{3}/)[0];
            string = string.match(/\d+/)[0].slice(-3);
        }catch(e){
            string = 1;
        }
        return parseInt(string);
    }

    function commentToUrl(comment){
        if(comment.indexOf("last:^") > -1){
            try{
                comment = comment.split("last:^")[1].split("^")[0];
                comment = comment.split("http://kissmanga.com")[1];
                comment = comment.split("#")[0];
            }catch(e){}
        }
        return comment;
    }

    function handleComment(update, current){
        var addition = 'last:^'+update+'^';
        if(current.indexOf("last:^") > -1){
            current = current.replace(/last:\^[^\^]*\^/,addition);
        }else{
            current = current+addition;
        }
        return current;
    }

    function handleanimeupdate( anime, current){
        if(listType == 'anime'){
            if(anime['checkIncrease'] === 1){
                if(current['.add_anime[num_watched_episodes]'] >= anime['.add_anime[num_watched_episodes]']){
                    if((anime['.add_anime[status]'] === 2 || current['.add_anime[status]'] === 2) && anime['.add_anime[num_watched_episodes]'] === 1){
                        if (confirm('Rewatch anime?')) {
                            anime['.add_anime[is_rewatching]'] = 1;
                        }else{
                            return null;
                        }
                    }else{
                        return null;
                    }
                }
                if(current['.add_anime[status]'] !== 2 && anime['.add_anime[num_watched_episodes]'] === current['totalEp']){
                    if (confirm('Set as completed?')) {
                        anime['.add_anime[status]'] = 2;
                        if(current['.add_anime[finish_date][day]'] === ''){
                            var Datec = new Date();
                            anime['.add_anime[finish_date][year]'] = Datec.getFullYear();
                            anime['.add_anime[finish_date][month]'] = Datec.getMonth()+1;
                            anime['.add_anime[finish_date][day]'] = Datec.getDate();
                        }
                    }
                }
                if(current['.add_anime[status]'] === 2 && anime['.add_anime[num_watched_episodes]'] === current['totalEp'] && current['.add_anime[is_rewatching]'] === 1){
                    if (confirm('Finish rewatching?')) {
                        anime['.add_anime[is_rewatching]'] = 0;
                        if(current['.add_anime[num_watched_times]'] === ''){
                            anime ['.add_anime[num_watched_times]'] = 1;
                        }else{
                            anime ['.add_anime[num_watched_times]'] = parseInt(current['.add_anime[num_watched_times]'])+1;
                        }
                    }
                }
                if(current['.add_anime[status]'] !== 1 && current['.add_anime[status]'] !== 2 && anime['.add_anime[status]'] !== 2){ 
                    if (confirm('Start watching?')) {
                        anime['.add_anime[status]'] = 1;
                        if(current['.add_anime[start_date][day]'] === ''){
                            var Datec = new Date();
                            anime['.add_anime[start_date][year]'] = Datec.getFullYear();
                            anime['.add_anime[start_date][month]'] = Datec.getMonth()+1;
                            anime['.add_anime[start_date][day]'] = Datec.getDate();
                        }
                    }
                }

            }
            return anime;
        }else{
            if(anime['checkIncrease'] === 1){
                current['checkIncrease'] = 1;
                if(current['.add_manga[num_read_chapters]'] >= anime['.add_manga[num_read_chapters]']){
                    if((anime['.add_manga[status]'] === 2 || current['.add_manga[status]'] === 2) && anime['.add_manga[num_read_chapters]'] === 1){
                        if (confirm('Reread Manga?')) {
                            anime['.add_manga[is_rereading]'] = 1;
                        }else{
                            current['.add_manga[comments]'] = anime['.add_manga[comments]'];
                            current['no_flash'] = 1;
                            anime = current;
                        }
                    }else{
                        current['.add_manga[comments]'] = anime['.add_manga[comments]'];
                        current['no_flash'] = 1;
                        anime = current;
                    }
                }
                if(current['.add_manga[status]'] !== 2 && anime['.add_manga[num_read_chapters]'] === current['totalChap']){
                    if (confirm('Set as completed?')) {
                        anime['.add_manga[status]'] = 2;
                        if(current['.add_manga[finish_date][day]'] === ''){
                            var Datec = new Date();
                            anime['.add_manga[finish_date][year]'] = Datec.getFullYear();
                            anime['.add_manga[finish_date][month]'] = Datec.getMonth()+1;
                            anime['.add_manga[finish_date][day]'] = Datec.getDate();
                        }
                    }
                }
                if(current['.add_manga[status]'] === 2 && anime['.add_manga[num_read_chapters]'] === current['totalChap'] && current['.add_manga[is_rereading]'] === 1){
                    if (confirm('Finish rereading?')) {
                        anime['.add_manga[is_rereading]'] = 0;
                        if(current['.add_manga[num_read_times]'] === ''){
                            anime ['.add_manga[num_read_times]'] = 1;
                        }else{
                            anime ['.add_manga[num_read_times]'] = parseInt(current['.add_manga[num_read_times]'])+1;
                        }
                    }
                }
                if(current['.add_manga[status]'] !== 1 && current['.add_manga[status]'] !== 2 && anime['.add_manga[status]'] !== 2){ 
                    if (confirm('Start reading?')) {
                        anime['.add_manga[status]'] = 1;
                        if(current['.add_manga[start_date][day]'] === ''){
                            var Datec = new Date();
                            anime['.add_manga[start_date][year]'] = Datec.getFullYear();
                            anime['.add_manga[start_date][month]'] = Datec.getMonth()+1;
                            anime['.add_manga[start_date][day]'] = Datec.getDate();
                        }
                    }
                }

            }
            return anime;
        }
    }

    function getcommondata(url){
        GM_xmlhttpRequest({
            method: "GET",
            url: url,
            synchronous: false,
            headers: {
                "User-Agent": "Mozilla/5.0"
            },
            onload: function(response) {
                var data = response.responseText;
                var rating = data.split('class="dark_text">Score')[1].split('<span')[1].split('>')[1].split('<')[0];
                $("#malRating").attr("href", url).text(rating);
            }
        });
    }

    function getanime(thisUrl , callback, absolute = false) {
        var thisUrl = thisUrl;
        var url = '';
        var malurl = '';
        var title = $.urlAnimeTitle(thisUrl);
        if(absolute === false){
            //url = "http://myanimelist.net/anime.php?q=" + encodeURI(formattitle(title));
            //url = "http://www.google.com/search?btnI&q=site:myanimelist.net/Anime/+-site:myanimelist.net/Anime/genre/+-site:myanimelist.net/anime/season/+"+encodeURI(formattitle(title));
            url = 'https://kissanimelist.firebaseio.com/Prototyp/'+dbSelector+'/'+encodeURIComponent($.titleToDbKey($.urlAnimeTitle(thisUrl)))+'/Mal.json';
            if(GM_getValue( dbSelector+'/'+$.titleToDbKey($.urlAnimeTitle(thisUrl))+'/Mal' , null) !== null ){
                if(con != console){
                    url = GM_getValue( dbSelector+'/'+$.titleToDbKey($.urlAnimeTitle(thisUrl))+'/Mal' , null);
                }
            }

            if(staticUrl(formattitle(title)) !== null){
                url = staticUrl(formattitle(title));
            }
        }else{
            url = absolute;
        }

        if(url === ''){
            $("#MalInfo").text("No Mal Entry!");
            return;
        }

        if(url.indexOf("myanimelist.net/"+listType+"/") > -1 && url.indexOf("google") === -1) {
            con.log("Mal: ", url);
            if(googleover === 0){
                local_setValue( thisUrl, url );
            }
            malurl = url;
            url = 'https://myanimelist.net/ownlist/'+listType+'/'+url.split('/')[4]+'/edit?hideLayout';//TODOsplit4 ersetzten
        }
        con.log("url",url);

        GM_xmlhttpRequest({
            method: "GET",
            url: url,
            synchronous: false,
            headers: {
                "User-Agent": "Mozilla/5.0"
            },
            onload: function(response) {
                url = response.finalUrl;
                url = firefoxUrl(url, response.responseText);
                if(url.split("/").length > 6 && url.indexOf("myanimelist.net/"+listType) > -1 && url.indexOf("google") === -1){
                    var partes = url.split("/");
                    url = partes[0]+"/"+partes[1]+"/"+partes[2]+"/"+partes[3]+"/"+partes[4]+"/"+partes[5];
                    getanime(thisUrl, callback, url);
                    return;
                }

                if(url.indexOf("kissanimelist.firebaseio.com") > -1) {
                    if(response.response !== 'null' && !(response.response.indexOf("error") > -1)){
                        //url = response.response.replace('"', '').replace('"', '');
                        url = 'https://myanimelist.net/'+listType+'/'+response.response.split('"')[1]+'/'+response.response.split('"')[3];
                        if(response.response.split('"')[1] == 'Not-Found'){
                            $("#MalInfo").text("Not Found!");
                            return;
                        }
                    }else{
                        url = "http://www.google.com/search?btnI&q="+googleMalUrl+encodeURI(formattitle(title));
                    }
                    getanime(thisUrl, callback, url);
                    return;
                }

                if(url.indexOf("ipv4.google.com") > -1) {
                    googleover = 1;
                    $.docReady(function() {
                        flashm( "Google Overloaded <br> <a target='_blank' href='"+url+"'>Solve captcha<a>" , true);
                        url = "http://myanimelist.net/"+listType+".php?q=" + encodeURI(formattitle(title));
                        getanime(thisUrl, callback, url);
                    });
                    return;
                }

                if(url.indexOf(listType+".php") > -1) {
                    var data = response.responseText;
                    var link = data.split(' <a class="hoverinfo_trigger" href="')[1].split('"')[0];
                    getanime(thisUrl, callback, link);
                    return;
                }

                if(url.indexOf("google.") > -1) {
                    googleover = 0;
                    var data = response.responseText;
                    if(data.indexOf("getElementById('captcha')") > -1){ //Firefox no absolute url workaround TODO:
                        googleover = 1;
                        $.docReady(function() {
                            flashm( "Google Overloaded", true);// <br> <a target='_blank' href='"+url+"'>Solve captcha<a>" , true);
                            url = "http://myanimelist.net/"+listType+".php?q=" + encodeURI(formattitle(title));
                            getanime(thisUrl, callback, url);
                        });
                        return;
                    }
                    try{
                        var link = data.split('class="g"')[1].split('a href="')[1].split('"')[0];
                        if(link.indexOf("/url?") > -1){
                            link = link.split("?q=")[1].split("&")[0];
                        }
                        getanime(thisUrl, callback, link);
                    }catch(e){
                        url = "http://myanimelist.net/"+listType+".php?q=" + encodeURI(formattitle(title));
                        getanime(thisUrl, callback, url);
                    }
                } else {
                    if(url.indexOf("myanimelist.net/"+listType+"/") > -1) {
                        con.log("Mal: ",url);
                        if(googleover === 0){
                            local_setValue( thisUrl, url );
                        }
                        getanime(thisUrl, callback, url);
                    }else{
                        if(url.indexOf("myanimelist.net/login.php") > -1) {
                            flashm( "Please log in on <a href='https://myanimelist.net/login.php'>MyAnimeList!<a>" , true);
                            var anime = {};
                            anime['login'] = 0;
                            anime['malurl'] = malurl;
                            $.docReady(function() {
                                callback(anime);
                            });
                        }else{
                            if(url.indexOf("myanimelist.net/"+listType+".php") > -1) {
                                $("#MalInfo").text("Not Found!");
                                flashm( "Anime not found" , true);
                                return;
                            }
                            con.log("MalEdit: ",url);
                            var anime = getObject(response.responseText,malurl);
                            $.docReady(function() {
                                callback(anime);
                            });
                        }
                    }
                }
            }
        });
    }



    function getObject(data,url){
        if(listType == 'anime'){
            //con.log(data);
            var anime = {};
            anime['malurl'] = url;
            anime['.csrf_token'] =  data.split('\'csrf_token\'')[1].split('\'')[1].split('\'')[0];
            if(data.indexOf('Add Anime') > -1) {
                anime['addanime'] = 1;
            }
            data = data.split('<form name="')[1].split('</form>')[0];

            anime['totalEp'] = parseInt(data.split('id="totalEpisodes">')[1].split('<')[0]);
            anime['name'] = data.split('<a href="')[1].split('">')[1].split('<')[0];
            anime['.anime_id'] = parseInt(data.split('name="anime_id"')[1].split('value="')[1].split('"')[0]); //input
            anime['.aeps'] = parseInt(data.split('name="aeps"')[1].split('value="')[1].split('"')[0]);
            anime['.astatus'] = parseInt(data.split('name="astatus"')[1].split('value="')[1].split('"')[0]);
            anime['.add_anime[status]'] = parseInt(getselect(data,'add_anime[status]'));
            //Rewatching
            if(data.split('name="add_anime[is_rewatching]"')[1].split('>')[0].indexOf('checked="checked"') >= 0){
                anime['.add_anime[is_rewatching]'] = 1;
            }
            //
            anime['.add_anime[num_watched_episodes]'] = parseInt(data.split('name="add_anime[num_watched_episodes]"')[1].split('value="')[1].split('"')[0]);
            if( isNaN(anime['.add_anime[num_watched_episodes]']) ){ anime['.add_anime[num_watched_episodes]'] = ''; }
            anime['.add_anime[score]'] = getselect(data,'add_anime[score]');
            anime['.add_anime[start_date][month]'] = getselect(data,'add_anime[start_date][month]');
            anime['.add_anime[start_date][day]'] = getselect(data,'add_anime[start_date][day]');
            anime['.add_anime[start_date][year]'] = getselect(data,'add_anime[start_date][year]');
            anime['.add_anime[finish_date][month]'] = getselect(data,'add_anime[finish_date][month]');
            anime['.add_anime[finish_date][day]'] = getselect(data,'add_anime[finish_date][day]');
            anime['.add_anime[finish_date][year]'] = getselect(data,'add_anime[finish_date][year]');
            anime['.add_anime[tags]'] = data.split('name="add_anime[tags]"')[1].split('>')[1].split('<')[0];//textarea
            anime['.add_anime[priority]'] = getselect(data,'add_anime[priority]');
            anime['.add_anime[storage_type]'] = getselect(data,'add_anime[storage_type]');
            anime['.add_anime[storage_value]'] = data.split('name="add_anime[storage_value]"')[1].split('value="')[1].split('"')[0];
            anime['.add_anime[num_watched_times]'] = data.split('name="add_anime[num_watched_times]"')[1].split('value="')[1].split('"')[0];
            anime['.add_anime[rewatch_value]'] = getselect(data,'add_anime[rewatch_value]');
            anime['.add_anime[comments]'] = data.split('name="add_anime[comments]"')[1].split('>')[1].split('<')[0];
            anime['.add_anime[is_asked_to_discuss]'] = getselect(data,'add_anime[is_asked_to_discuss]');
            anime['.add_anime[sns_post_type]'] = getselect(data,'add_anime[sns_post_type]');
            anime['.submitIt'] = data.split('name="submitIt"')[1].split('value="')[1].split('"')[0];
            con.log(anime);
            return anime;
        }else{
            //con.log(data);
            var anime = {};
            anime['malurl'] = url;
            anime['.csrf_token'] =  data.split('\'csrf_token\'')[1].split('\'')[1].split('\'')[0];
            if(data.indexOf('Add Manga') > -1) {
                anime['addmanga'] = 1;
            }
            data = data.split('<form name="')[1].split('</form>')[0];

            anime['totalVol'] = parseInt(data.split('id="totalVol">')[1].split('<')[0]);
            anime['totalChap'] = parseInt(data.split('id="totalChap">')[1].split('<')[0]);
            anime['name'] = data.split('<a href="')[1].split('">')[1].split('<')[0];
            anime['.entry_id'] = parseInt(data.split('name="entry_id"')[1].split('value="')[1].split('"')[0]);
            anime['.manga_id'] = parseInt(data.split('name="manga_id"')[1].split('value="')[1].split('"')[0]); //input
            anime['volumes'] = parseInt(data.split('id="volumes"')[1].split('value="')[1].split('"')[0]);
            anime['mstatus'] = parseInt(data.split('id="mstatus"')[1].split('value="')[1].split('"')[0]);
            anime['.add_manga[status]'] = parseInt(getselect(data,'add_manga[status]'));
            //Rewatching
            if(data.split('name="add_manga[is_rereading]"')[1].split('>')[0].indexOf('checked="checked"') >= 0){
                anime['.add_manga[is_rereading]'] = 1;
            }
            //
            anime['.add_manga[num_read_volumes]'] = parseInt(data.split('name="add_manga[num_read_volumes]"')[1].split('value="')[1].split('"')[0]);
            if( isNaN(anime['.add_manga[num_read_volumes]']) ){ anime['.add_manga[num_read_volumes]'] = ''; }
            anime['.add_manga[num_read_chapters]'] = parseInt(data.split('name="add_manga[num_read_chapters]"')[1].split('value="')[1].split('"')[0]);
            if( isNaN(anime['.add_manga[num_read_chapters]']) ){ anime['.add_manga[num_read_chapters]'] = ''; }
            anime['.add_manga[score]'] = getselect(data,'add_manga[score]');
            anime['.add_manga[start_date][month]'] = getselect(data,'add_manga[start_date][month]');
            anime['.add_manga[start_date][day]'] = getselect(data,'add_manga[start_date][day]');
            anime['.add_manga[start_date][year]'] = getselect(data,'add_manga[start_date][year]');
            anime['.add_manga[finish_date][month]'] = getselect(data,'add_manga[finish_date][month]');
            anime['.add_manga[finish_date][day]'] = getselect(data,'add_manga[finish_date][day]');
            anime['.add_manga[finish_date][year]'] = getselect(data,'add_manga[finish_date][year]');
            anime['.add_manga[tags]'] = data.split('name="add_manga[tags]"')[1].split('>')[1].split('<')[0];//textarea
            anime['.add_manga[priority]'] = getselect(data,'add_manga[priority]');
            anime['.add_manga[storage_type]'] = getselect(data,'add_manga[storage_type]');
            anime['.add_manga[num_retail_volumes]'] = data.split('name="add_manga[num_retail_volumes]"')[1].split('value="')[1].split('"')[0];
            anime['.add_manga[num_read_times]'] = data.split('name="add_manga[num_read_times]"')[1].split('value="')[1].split('"')[0];
            anime['.add_manga[reread_value]'] = getselect(data,'add_manga[reread_value]');
            anime['.add_manga[comments]'] = data.split('name="add_manga[comments]"')[1].split('>')[1].split('<')[0];
            anime['.add_manga[is_asked_to_discuss]'] = getselect(data,'add_manga[is_asked_to_discuss]');
            anime['.add_manga[sns_post_type]'] = getselect(data,'add_manga[sns_post_type]');
            anime['.submitIt'] = data.split('name="submitIt"')[1].split('value="')[1].split('"')[0];
            con.log(anime);
            return anime;
        }
    }

    function setanime(thisUrl ,anime, actual = null) {

        if(actual === null){
            getanime(thisUrl, function(actual){setanime(thisUrl , anime, actual);});
            return;
        }

        if(listType == 'anime'){
            var url = "https://myanimelist.net/editlist.php?type=anime&id="+actual['.anime_id'];
            if(actual['addanime'] === 1){
                url = "https://myanimelist.net/ownlist/anime/add?selected_series_id="+actual['.anime_id'];
                if (!confirm('Add "'+actual['name']+'" to MAL?')) {
                    return;
                }
            }
        }else{
            var url = "https://myanimelist.net/panel.php?go=editmanga&id="+actual['.manga_id'];
            if(actual['addmanga'] === 1){
                url = "https://myanimelist.net/ownlist/manga/add?selected_manga_id="+actual['.manga_id'];
                if (!confirm('Add "'+actual['name']+'" to MAL?')) {
                    return;
                }
            }
        }

        anime = handleanimeupdate( anime, actual );
        if(anime === null){
            return;
        }
        $.each( anime, function( index, value ){
            actual[index] = value;
        });
        anime = actual;
        var parameter = "";


        $.each( anime, function( index, value ){
            if(index.charAt(0) == "."){
                if(!(index === '.add_anime[is_rewatching]' && anime[index] === 0)){
                    parameter += encodeURIComponent (index.substring(1))+"="+encodeURIComponent (value)+"&";
                }
                if(!(index === '.add_manga[is_rereading]' && anime[index] === 0)){
                    parameter += encodeURIComponent (index.substring(1))+"="+encodeURIComponent (value)+"&";
                }
            }
        });

        GM_xmlhttpRequest({
            method: "POST",
            url: url,
            synchronous: false,
            data: parameter,
            headers: {
                "User-Agent": "Mozilla/5.0",
                "Content-Type": "application/x-www-form-urlencoded",
                "accept":"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8"
            },
            onload: function(response) {
                //con.log(response);//.responseText);
                if(anime['no_flash'] !== 1){
                    if(response.responseText.indexOf('Successfully') >= 0){
                        if(listType == 'anime'){
                            flashm( anime['name']+" ("+anime['.add_anime[num_watched_episodes]']+"/"+anime['totalEp']+")" , false);
                        }else{
                            flashm( anime['name']+" ("+anime['.add_manga[num_read_volumes]']+"/"+anime['totalVol']+")"+" ("+anime['.add_manga[num_read_chapters]']+"/"+anime['totalChap']+")" , false);
                        }
                        if($("#malbutton").height()!==null){
                            $("#malbutton").attr("value","");
                            $("#malEpisodes").prop("disabled",false);
                            $("#malEpisodes").css('border-width','1px');
                            $("#malVolumes").prop("disabled",false);
                            $("#malVolumes").css('border-width','1px');
                            $("#malChapters").prop("disabled",false);
                            $("#malChapters").css('border-width','1px');
                            $("#malUserRating").prop("disabled",false);
                            $("#malUserRating").css('border-width','1px');
                            $("#malStatus").prop("disabled",false);
                            $("#malStatus").css('border-width','1px');
                        }
                    }else{
                        flashm( "Anime update failed" , true);
                        if($("#malbutton").height()!==null){
                            $("#malbutton").prop("disabled",false);
                            $("#malbutton").attr("value","update");
                            $("#malbutton").css('border-width','1px');
                            $("#malEpisodes").prop("disabled",false);
                            $("#malEpisodes").css('border-width','1px');
                            $("#malVolumes").prop("disabled",false);
                            $("#malVolumes").css('border-width','1px');
                            $("#malChapters").prop("disabled",false);
                            $("#malChapters").css('border-width','1px');
                            $("#malUserRating").prop("disabled",false);
                            $("#malUserRating").css('border-width','1px');
                            $("#malStatus").prop("disabled",false);
                            $("#malStatus").css('border-width','1px');
                        }  
                    }
                }
                if(anime['checkIncrease'] !== 1){
                    try{
                        checkdata();
                    }catch(e){}
                }
            }
        });

    }

    //#####################

    function firefoxUrl(url, html){
        if(html.indexOf('property="og:url"') > -1){
            url = html.split('<meta property="og:url"')[1].split('content="')[1].split('"')[0];
        }
        return url;
    }

    function staticUrl(title){
        switch(title) {
            case 'Blood': return 'https://myanimelist.net/anime/150/Blood_';
            case 'K': return 'https://myanimelist.net/anime/14467/K';
            case 'Morita-san-wa-Mukuchi': return 'https://myanimelist.net/anime/10671/Morita-san_wa_Mukuchi';
            default:  return null;
        }
    }

    function local_setValue( thisUrl, malurl ){
        if(GM_getValue(dbSelector+'/'+$.titleToDbKey($.urlAnimeTitle(thisUrl))+'/Mal' , null) == null || thisUrl.slice(-1) == '#'){
            var param = { Kiss: thisUrl, Mal: malurl};
            $.ajax({
                url: 'https://kissanimelist.firebaseio.com/Request/'+dbSelector+'Request.json',
                type: "POST",
                data: JSON.stringify(param),
                success: function () {
                    con.log("Send to database: ",param);
                },
                error: function(error) {
                    con.log("Send to database: ",error);
                }
            });
        }
        GM_setValue( dbSelector+'/'+$.titleToDbKey($.urlAnimeTitle(thisUrl))+'/Mal', malurl );
    }

    function getselect(data, name){
        var temp = data.split('name="'+name+'"')[1].split('</select>')[0];
        if(temp.indexOf('selected="selected"') > -1){
            temp = temp.split('<option');
            for (var i = 0; i < temp.length; ++i) {
                if(temp[i].indexOf('selected="selected"') > -1){
                    return temp[i].split('value="')[1].split('"')[0];
                }
            }
        }else{
            return '';
        }
    }

    function flashm(text,error = true){
        if(error === true){
            $('#flash').css("background","rgba(227, 0, 0, 0.6)");
        }else{
            $('#flash').css("background","rgba(0,227,30, 0.6)");
        }
        con.log("Flash Message: ",text);
        $('#flash').html(text).fadeIn(800).delay(4000).fadeOut(800);
    }

    function updatebutton(){//TODO when sending
        if($("#malbutton").height()===null){
            $("#malp").append("&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<input type='button' value='update' id='malbutton' style='background-color: transparent; border-width: 1px; border-color: grey; color: "+textColor+"; text-decoration: none; outline: medium none;'>");
            $("#malbutton").click(function() {
                buttonclick();
            });
        }else{
            $("#malbutton").prop("disabled",false);
            $("#malbutton").attr("value","update");
            $("#malbutton").css('border-width','1px');
        }
    }

    function buttonclick(){
        $("#malbutton").prop("disabled",true);
        $("#malbutton").attr("value","Sending");
        $("#malbutton").css('border-width','0');
        $("#malEpisodes").prop("disabled",true);
        $("#malEpisodes").css('border-width','0');
        $("#malVolumes").prop("disabled",true);
        $("#malVolumes").css('border-width','0');
        $("#malChapters").prop("disabled",true);
        $("#malChapters").css('border-width','0');
        $("#malUserRating").prop("disabled",true);
        $("#malUserRating").css('border-width','0');
        $("#malStatus").prop("disabled",true);
        $("#malStatus").css('border-width','0');
        var anime = {};
        if(listType == 'anime'){
            anime['.add_anime[num_watched_episodes]'] = $("#malEpisodes").val();  
        }else{
            anime['.add_manga[num_read_volumes]'] = $("#malVolumes").val();
            anime['.add_manga[num_read_chapters]'] = $("#malChapters").val();
        }
        anime['.add_'+listType+'[score]'] = $("#malUserRating").val();
        anime['.add_'+listType+'[status]'] = $("#malStatus").val();

        setanime($.normalUrl(), anime);
    }

    function formattitle(title) {
        con.log("Title: ",title);

        if(title.substr(title.length - 4)=="-Dub"){
            title=title.slice(0,-4);
        }
        if(title.substr(title.length - 4)=="-Sub"){
            title=title.slice(0,-4);
        }

        title = title.replace(' ','-');
        title = title.replace(' ','-');
        title = title.replace(' ','-');
        title = title.replace(' ','-');
        title = title.replace(' ','-');
        title = title.replace(' ','-');
        title = title.replace(' ','-');
        title = title.replace(' ','-');
        title = title.replace(' ','-');
        title = title.replace(" s2"," 2nd season");
        title = title.replace(" s3"," 3nd season");
        title = title.replace(" s4"," 4nd season");
        title = title.replace(" s5"," 5nd season");
        title = title.replace(" s6"," 6nd season");
        title = title.replace(" s7"," 7nd season");
        title = title.replace(" s8"," 8nd season");
        title = title.replace(" s9"," 9nd season");
        //title = title.replace(/[-,.?:'"\\!@#$%^&\-_=+`~;]/g,"");
        con.log("Formated: ",title);
        return title;
    }
    //init

    function checkdata(){
        if($.normalUrl() !== ""){
            getanime($.normalUrl(), function(anime){handleanime(anime);});
        }else{
            alert(error);
        }

        $.docReady(function() {
            if(listType == 'anime'){
                var spacer = '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp';
                var middle = '';
                middle += '<span class="info">Episodes: </span>';
                middle += '<span style="color: '+textColor+'; text-decoration: none; outline: medium none;">';
                middle += '<input id="malEpisodes" value="0" style="background: transparent; border-width: 1px; border-color: grey; text-align: right; color: '+textColor+'; text-decoration: none; outline: medium none;" type="text" size="1" maxlength="4">';
                middle += '/<span id="malTotal">0</span>';
                middle += '</span>';

            }else{
                var spacer = '&nbsp;&nbsp;&nbsp;&nbsp';
                var middle = '';
                middle += '<span class="info">Volumes: </span>';
                middle += '<span style="color: '+textColor+'; text-decoration: none; outline: medium none;">';
                middle += '<input id="malVolumes" value="0" style="background: transparent; border-width: 1px; border-color: grey; text-align: right; color: '+textColor+'; text-decoration: none; outline: medium none;" type="text" size="1" maxlength="4">';
                middle += '/<span id="malTotalVol">0</span>';
                middle += '</span>';

                middle += spacer;

                middle += '<span class="info">Chapters: </span>';
                middle += '<span style="color: '+textColor+'; text-decoration: none; outline: medium none;">';
                middle += '<input id="malChapters" value="0" style="background: transparent; border-width: 1px; border-color: grey; text-align: right; color: '+textColor+'; text-decoration: none; outline: medium none;" type="text" size="1" maxlength="4">';
                middle += '/<span id="malTotalCha">0</span>';
                middle += '</span>';
            }
            var ui = '<p id="malp">';
            ui += '<span id="MalInfo">Loading</span>';

            ui += '<span id="MalData" style="display: none;">';

            ui += '<span class="info">Mal Score: </span>';
            ui += '<a id="malRating" style="color: '+textColor+';" target="_blank" href=""></a>';

            ui += '<span id="MalLogin">';

            ui += spacer;

            ui += '<span class="info">Status: </span>';
            ui += '<select id="malStatus" style="font-size: 12px;background: transparent; border-width: 1px; border-color: grey; color: '+textColor+'; text-decoration: none; outline: medium none;">';
            ui += '<option value="0" style="background: #111111;color: '+textColor+';"></option>';
            ui += '<option value="1" style="background: #111111;color: '+textColor+';">Watching</option>';
            ui += '<option value="2" style="background: #111111;color: '+textColor+';">Completed</option>';
            ui += '<option value="3" style="background: #111111;color: '+textColor+';">On-Hold</option>';
            ui += '<option value="4" style="background: #111111;color: '+textColor+';">Dropped</option>';
            ui += '<option value="6" style="background: #111111;color: '+textColor+';">Plan to Watch</option>';
            ui += '</select>';

            ui += spacer;

            ui += middle;

            ui += spacer;

            ui += '<span class="info">Your Score: </span>';

            ui += '<select id="malUserRating" style="font-size: 12px;background: transparent; border-width: 1px; border-color: grey; color: '+textColor+'; text-decoration: none; outline: medium none;"><option value="" style="background: #111111;color: '+textColor+';">Select</option>';
            ui += '<option value="10" style="background: #111111;color: '+textColor+';">(10) Masterpiece</option>';
            ui += '<option value="9" style="background: #111111;color: '+textColor+';">(9) Great</option>';
            ui += '<option value="8" style="background: #111111;color: '+textColor+';">(8) Very Good</option>';
            ui += '<option value="7" style="background: #111111;color: '+textColor+';">(7) Good</option>';
            ui += '<option value="6" style="background: #111111;color: '+textColor+';">(6) Fine</option>';
            ui += '<option value="5" style="background: #111111;color: '+textColor+';">(5) Average</option>';
            ui += '<option value="4" style="background: #111111;color: '+textColor+';">(4) Bad</option>';
            ui += '<option value="3" style="background: #111111;color: '+textColor+';">(3) Very Bad</option>';
            ui += '<option value="2" style="background: #111111;color: '+textColor+';">(2) Horrible</option>';
            ui += '<option value="1" style="background: #111111;color: '+textColor+';">(1) Appalling</option>';
            ui += '</select>';
            ui += '</span>';
            ui += '</span>';
            ui += '</p>';

            var uihead ='';
            uihead += '<p class="headui" style="float: right; margin: 0; margin-right: 10px">';
            uihead += '';
            uihead += '<p>';

            var uiwrong ='';
            uiwrong += '<a id="malWrong" href="#" style="display: inline; margin-left: 6px;">';
            uiwrong += '[Mal incorrect?]';
            uiwrong += '</a>';
            uiwrong += '<a id="episodeOffset" href="#" onclick="return false;" style="display: inline; margin-left: 6px;">';
            uiwrong += '[Episode Offset]';
            uiwrong += '</a>';


            if($("#flash").width() === null){
                $(ui).uiPos();
                $(uiwrong).uiWrongPos();
                $(uihead).uiHeadPos();
                var flashpos = $('body');
                if($('#my_video_1').width() !== null){
                    flashpos = $('#my_video_1');
                }
                flashpos.prepend('<div style="text-align: center;position: fixed;bottom:10px;width:100%;z-index: 100000;left: 0;"><div id="flash" style="display:none;  background-color: red;padding: 20px; margin: 0 auto;max-width: 60%;          -webkit-border-radius: 20px;-moz-border-radius: 20px;border-radius: 20px;background:rgba(227,0,0,0.6);                       "></div></div>');
                $("#malWrong").click(function() {
                    var murl = GM_getValue(dbSelector+'/'+$.titleToDbKey($.urlAnimeTitle($.normalUrl()))+'/Mal' , null);
                    murl = prompt("Please enter the right MyAnimeList url. \nLeave blank for reset",murl);
                    if(murl !== null){
                        if(murl !== ''){
                            GM_setValue( dbSelector+'/'+$.titleToDbKey($.urlAnimeTitle($.normalUrl()))+'/Mal', murl );
                            flashm( "new url '"+murl+"' set." , false);
                            checkdata();
                        }else{
                            GM_deleteValue( dbSelector+'/'+$.titleToDbKey($.urlAnimeTitle($.normalUrl()))+'/Mal' );
                            flashm( "MyAnimeList url reset" , false);
                            checkdata();
                        }
                    }
                });
                $("#episodeOffset").click(function() {
                    var Offset = GM_getValue(dbSelector+'/'+$.titleToDbKey($.urlAnimeTitle($.normalUrl()))+'/Offset' , null);
                    Offset = prompt("Please enter the Episode Offset. \nDont forget to use '-' !",Offset);
                    if(Offset !== null){
                        if(Offset !== ''){
                            GM_setValue( dbSelector+'/'+$.titleToDbKey($.urlAnimeTitle($.normalUrl()))+'/Offset', Offset );
                            flashm( "New Offset ("+Offset+") set." , false);
                            checkdata();
                        }else{
                            GM_deleteValue( dbSelector+'/'+$.titleToDbKey($.urlAnimeTitle($.normalUrl()))+'/Offset' );
                            flashm( "Offset reset" , false);
                            checkdata();
                        }
                    }
                });
                //#######Kissanime#######
                $("#btnRemoveBookmark").click(function() {
                    var anime = {};
                    anime['.add_'+listType+'[status]'] = 4;
                    setanime($.normalUrl(),anime);
                });

                $("#btnAddBookmark").click(function() {
                    var anime = {};
                    anime['.add_'+listType+'[status]'] = 6;
                    setanime($.normalUrl(),anime);
                });
                //#######################
            }
        });


    }

    //######## Bookmarks ########
    
    var xml ="";
    var foundAnime = [];

    //var imageBackup = "Mal-img";
    var image = "image";

    function getMalXml(user = ""){
        var url = "https://myanimelist.net/editprofile.php?go=privacy";
        if(user !== ""){
            url = "https://myanimelist.net/malappinfo.php?u="+user+"&status=all&type="+listType;
            con.log("XML Url:", url);
        }
        GM_xmlhttpRequest({
            method: "GET",
            url: url,
            synchronous: false,
            headers: {
                "User-Agent": "Mozilla/5.0"
            },
            onload: function(response) {
                if(url ===  "https://myanimelist.net/editprofile.php?go=privacy"){
                    try{
                        user = response.responseText.split('<a href="https://myanimelist.net/profile/')[1].split('"')[0];
                    }catch(e){
                        flashm( "Please log in on <a href='https://myanimelist.net/login.php'>MyAnimeList!<a>" , true);
                        $('.listing tr td:nth-child(1)').css('height', 'initial');
                        $('.listing tr td:nth-child(1)').css('padding-left', '0');
                        return;
                    }
                    con.log("User:" ,user);
                    getMalXml(user);
                    return;
                }
                xml = $(response.responseXML);
                setAll();
            }
        });
    }

    function encodeurl(string){
        return encodeURIComponent(encodeURIComponent(string).replace('.', '%2E'));
    }

    function setBookmarkAnime(value, baseurl, target, last = 0){
        var id = value.split("/")[4];
        con.log(id);
        foundAnime.push(id);
        var xmlAnime = xml.find('series_'+listType+'db_id:contains('+id+')').parent();

        getdata(baseurl, function(value) { setimage(value, xmlAnime, target, baseurl); }, image);

        if(xmlAnime.length === 0){
            if(id == 'Not-Found'){
                target.find(".MalData").first().append("No Mal");
            }else{
                target.find(".MalData").first().append("<a href='#' onclick='return false;'>Add to Mal</a>").find("a").click(function() {
                    var anime = {};
                    anime['.add_'+listType+'[status]'] = 6;
                    setanime(baseurl,anime);
                });
            }
        }else{
            var totalEp = xmlAnime.find("series_"+middleType).first().text();
            if(totalEp === '0'){
                totalEp = "?";
            }
            
            setepisode (xmlAnime.find("my_"+middleVerb+"_"+middleType).first().text(), totalEp , target, baseurl);
            setstatus (xmlAnime.find("my_status").first().text() , target, baseurl);
            setscore (xmlAnime.find("my_score").first().text() , target, baseurl);
        }
        if(last === 1){ //TODO: 
            con.log(foundAnime);
            //MalExistsOnKiss(foundAnime);
        }
    }

    function setimage(value, xmlAnime, target, baseurl){
        if(classicBookmarks == 0){
            if(typeof value === "undefined" || value === null){
                if(baseurl === ""){
                    return;
                }
                //getdata(baseurl, function(value) { setimage(value, xmlAnime, target, ""); }, imageBackup);
                return;
            }
            target.find("td").first().html("<img src='"+value+"' width='120px' height='150px'></img>");
            /*target.find("td").first().find("img").error(function() {
                //TODO: Send to Database and only execute one time so no loop
                getdata(baseurl, function(value) { setimage(value, xmlAnime, target, ""); }, imageBackup);
            });*/
        }
    }

    function setepisode(episode, totalEp, target, baseurl){
        target.find(".MalData").first().append('<div class="malEpisode"><input class="input" type="number" min="0" max="'+totalEp+'" value="'+episode+'" size="1" maxlength="4" style="display: none;background: transparent; border-width: 1px; border-color: grey; text-align: right; color: '+textColor+'; text-decoration: none; outline: medium none; max-width: 50px;"/><span class="normal">'+episode+'</span> / '+totalEp+'</div>');

        target.find(".MalData").first().find('.malEpisode').click(
          function() {
            $( this ).find('.input').css('display', 'initial');
            $( this ).find('.normal').css('display', 'none');
          }).change(function() {
            var anime = {};
            anime['.add_'+listType+'[num_'+middleVerb+'_'+middleType+']'] = $(this).parent().find('.malEpisode').find('.input').val();
            anime['.add_'+listType+'[status]'] = $(this).parent().find('.malStatus').val();
            anime['.add_'+listType+'[score]'] = $(this).parent().find('.malUserRating').val();
            setanime(baseurl,anime);
          });
    }

    function setstatus(value, target, baseurl){
        if(target.find(".malStatus").first().height() === null){
            var ui = "";
            ui += '<select class="malStatus" style="width: 100%; font-size: 12px; background: transparent; border-width: 0px; border-color: grey; color: '+textColor+'; text-decoration: none; outline: medium none;">';
            //ui += '<option value="0" style="background: #111111;color: #d5f406;"></option>';
            ui += '<option value="1" style="background: #111111;color: '+textColor+';">Watching</option>';
            ui += '<option value="2" style="background: #111111;color: '+textColor+';">Completed</option>';
            ui += '<option value="3" style="background: #111111;color: '+textColor+';">On-Hold</option>';
            ui += '<option value="4" style="background: #111111;color: '+textColor+';">Dropped</option>';
            ui += '<option value="6" style="background: #111111;color: '+textColor+';">Plan to Watch</option>';
            ui += '</select>';
            target.find(".MalData").first().append(""+ui).find('.malStatus').change(function() {
                var anime = {};
                anime['.add_'+listType+'[num_'+middleVerb+'_'+middleType+']'] = $(this).parent().find('.malEpisode').find('.input').val();
                anime['.add_'+listType+'[status]'] = $(this).parent().find('.malStatus').val();
                anime['.add_'+listType+'[score]'] = $(this).parent().find('.malUserRating').val();
                setanime(baseurl,anime);
            });
        }
        target.find(".malStatus").first().val(value);
    }

    function setscore(value, target, baseurl){
        if(target.find(".malUserRating").first().height() === null){
            var ui = "";
            ui += '<select class="malUserRating" style="width: 100%; font-size: 12px; background: transparent; border-width: 0px; border-color: grey; color: '+textColor+'; text-decoration: none; outline: medium none;"><option value="" style="background: #111111;color: '+textColor+';">Select</option>';
            ui += '<option value="10" style="background: #111111;color: '+textColor+';">(10) Masterpiece</option>';
            ui += '<option value="9" style="background: #111111;color: '+textColor+';">(9) Great</option>';
            ui += '<option value="8" style="background: #111111;color: '+textColor+';">(8) Very Good</option>';
            ui += '<option value="7" style="background: #111111;color: '+textColor+';">(7) Good</option>';
            ui += '<option value="6" style="background: #111111;color: '+textColor+';">(6) Fine</option>';
            ui += '<option value="5" style="background: #111111;color: '+textColor+';">(5) Average</option>';
            ui += '<option value="4" style="background: #111111;color: '+textColor+';">(4) Bad</option>';
            ui += '<option value="3" style="background: #111111;color: '+textColor+';">(3) Very Bad</option>';
            ui += '<option value="2" style="background: #111111;color: '+textColor+';">(2) Horrible</option>';
            ui += '<option value="1" style="background: #111111;color: '+textColor+';">(1) Appalling</option>';
            ui += '</select>';
            target.find(".MalData").first().append("</br>"+ui).find('.malUserRating').change(function() {
                var anime = {};
                anime['.add_'+listType+'[num_'+middleVerb+'_'+middleType+']'] = $(this).parent().find('.malEpisode').find('.input').val();
                anime['.add_'+listType+'[status]'] = $(this).parent().find('.malStatus').val();
                anime['.add_'+listType+'[score]'] = $(this).parent().find('.malUserRating').val();
                setanime(baseurl,anime);
            });
        }
        target.find(".malUserRating").first().val(value);
    }

    function clearCache(){
        con.log('Before',GM_listValues());
        var cacheArray = GM_listValues();
        $.each( cacheArray, function( index, cache){
            if(/^[^/]+\/[^/]+\/Mal$/.test(cache)){
                GM_deleteValue(cache);
            }
            if(/^[^/]+\/[^/]+\/bdid$/.test(cache)){
                GM_deleteValue(cache);
            }
            if(/^[^/]+\/[^/]+\/image$/.test(cache)){
                GM_deleteValue(cache);
            }
        });
        con.log('After',GM_listValues());
        flashm( "Cache Cleared" , false);
    }

    function MalExistsOnKiss(animelist){
        var row = "";
        var xmlEntry = "";
        $(".listing").html("");//TODO remove;
        xml.find('series_'+listType+'db_id').each(function(index){
            if((jQuery.inArray( $(this).text(), animelist ) ) < 0){
                con.log($(this).text());
                xmlEntry = $(this).parent();
                row = "";
                row += '<tr class="trAnime">';
                row += '<td class="Timage" style="padding-left: 0px; height: 150px; vertical-align: top;">';
                row += '<img src="'+xmlEntry.find("series_image").first().text()+'" width="120px" height="150px">';
                row += '</td>';
                row += '<td style="vertical-align: top;">';
                row += '<div class="title" style="padding-bottom: 10px;">';
                row += '<a class="aAnime" href="https://myanimelist.net/'+listType+'/'+xmlEntry.find("series_"+listType+"db_id").first().text()+'">'+xmlEntry.find("series_title").first().text()+'</a>';
                row += '</div>';
                row += '</td>';
                row += '</tr>';

                $(".listing").before(row);
            }
        });
        
        
    }

    function getdata(baseurl, callback, parth = ""){
        if(GM_getValue(dbSelector+'/'+$.titleToDbKey($.urlAnimeTitle(baseurl))+'/'+parth , null) !== null ){
            con.log("cache:", dbSelector+'/'+$.titleToDbKey($.urlAnimeTitle(baseurl))+'/'+parth);
            var value = GM_getValue( dbSelector+'/'+$.titleToDbKey($.urlAnimeTitle(baseurl))+'/'+parth , null);
            callback(value);
        }else{
            con.log("db:", dbSelector+'/'+$.titleToDbKey($.urlAnimeTitle(baseurl))+'/'+parth);
            var url = 'https://kissanimelist.firebaseio.com/Prototyp/'+dbSelector+'/'+encodeURIComponent(encodeURIComponent($.titleToDbKey($.urlAnimeTitle(baseurl)))).toLowerCase()+'/'+parth+'.json';
            GM_xmlhttpRequest({
                method: "GET",
                url: url,
                synchronous: false,
                headers: {
                    "User-Agent": "Mozilla/5.0"
                },
                onload: function(response) {
                    //con.log(response);
                    if( response.responseText != null  && response.responseText != 'null'){
                        var newResponse = response.responseText.slice(1, -1);
                        if(parth == 'Mal'){
                            newResponse = 'https://myanimelist.net/'+listType+'/'+response.responseText.split('"')[1]+'/'+response.responseText.split('"')[3];
                        }
                        GM_setValue(dbSelector+'/'+$.titleToDbKey($.urlAnimeTitle(baseurl))+'/'+parth , newResponse);
                        callback(newResponse);
                    }
                }
            });
        }
    }

    function setAll(){
        $.docReady(function() {

            $.bookmarkEntrySelector().each(function() {
                var thistd = $(this).find("td").first();
                $(this).find("td").first().children().first().wrap('<div class="title" style="padding-bottom: 10px;"></div>');
                var append = '<div style="width: 50%; float: left;" class="kissData"></div><div style="width: 50%; float: left;" class="MalData"></div>';
                $(this).find("td").first().append(append);


                $(this).find("td").each(function(index){
                    
                    if(index > 0){
                        $(this).appendTo(thistd.find(".kissData"));
                        //text += $(this).html()+"<br/>";
                        //$(this).remove();
                    }else{
                        //text += '<div class="title" style="padding-bottom: 10px;">'+$(this).html()+'</div><div style="width: 50%; float: left;" class="kiss">';
                    }
                });
                $(this).find("td").first().find("td").append("<br />").contents().unwrap();
            });
            if($("#cssTableSet").height() === null){
                $.BookmarksStyleAfterLoad(); 
            }else{
                return;
            }

            var len = $.bookmarkEntrySelector().length;
            $.bookmarkEntrySelector().bind('inview', function (event, visible) {
                if (visible === true) {
                    var baseurl = $.absoluteLink($(this).find("a").first().attr('href'));
                    var target = $(this);
                    getdata(baseurl,function(value) { setBookmarkAnime(value, baseurl, target); }, "Mal");
                    $(this).unbind('inview');
                }
            });
            $(window).scroll();
        });
    }

    //####Kiss2Mal####
    function getSites(sites, page){
        $.each(sites, function(index, value){
            con.log( index + ": " + value );
            $.ajax({
                url: 'https://kissanimelist.firebaseio.com/Prototyp/'+value+'/'+encodeURIComponent(index)+'.json',
                type: "GET",
                success: function (response) {
                    con.log(response);
                    if(response != null){
                        if($('#'+page+'Links').width() == null){
                            $('#siteSearch').before('<h2 id="'+page+'Links">'+page+'</h2><br>');
                        }
                        $('#'+page+'Links').after('<div><a target="_blank" href="'+response['url']+'">'+response['title']+'</a><div>');
                    }
                },
                error: function(error) {
                    con.log("error: "+error);
                }
            });
        });
    }

    function setKissToMal(){
        $(document).ready(function() {
            var type = window.location.href.split('/')[3];
            var uid = window.location.href.split('/')[4];
            $('h2:contains("Information")').before('<h2 id="siteSearch">Search</h2><br>');
            if(type == 'anime'){
                $('#siteSearch').after('<div><a target="_blank" href="https://www.masterani.me/anime?search='+$('#contentWrapper > div:first-child span').text()+'">Masterani</a></div>');
                $('#siteSearch').after('<form target="_blank" action="http://kissanime.ru/Search/Anime" id="kissanimeSearch" method="post" _lpchecked="1"><a href="#" onclick="return false;" class="submitKissanimeSearch">Kissanime</a><input type="hidden" id="keyword" name="keyword" value="'+$('#contentWrapper > div:first-child span').text()+'"/></form>');
                $('.submitKissanimeSearch').click(function(){
                  $('#kissanimeSearch').submit();
                });
            }else{
                $('#siteSearch').after('<form target="_blank" action="http://kissmanga.com/Search/Manga" id="kissmangaSearch" method="post" _lpchecked="1"><a href="#" onclick="return false;" class="submitKissmangaSearch">Kissmanga</a><input type="hidden" id="keyword" name="keyword" value="'+$('#contentWrapper > div:first-child span').text()+'"/></form>');
                $('.submitKissmangaSearch').click(function(){
                  $('#kissmangaSearch').submit();
                });
            }
            $.each( [ 'Kissanime', 'Kissmanga', 'Masterani'], function( index, page ){            
                var url = 'https://kissanimelist.firebaseio.com/Prototyp/Mal'+type+'/'+uid+'/Sites/'+page+'.json';
                $.ajax({
                    url: url,
                    type: "GET",
                    success: function (response) {
                        con.log('Url',url);
                        con.log(response);
                        if(response != null){
                            getSites(response, page);
                        }                        
                    },
                    error: function(error) {
                        con.log("error: "+error);
                    }
                });
            });
       });
    }
    //######Bookmark Dropdown#######
    if(dbSelector == 'Kissanime'){
        $( document).ready( function(){
            if( window.location.href.indexOf("BookmarkList") > -1 ){
                var catOptions = '';
                catOptions +='<option value="">Select</option>';
                $.each(lstCats, function( index, value ) {
                  catOptions +='<option value="'+value+'">'+value+'</option>';
                });
                catOptions = '<select class="selectCats" style="width: 200px; font-size: 14px;">'+catOptions+'</select>';
                con.log(catOptions);
                GM_setValue(dbSelector+'catOptions',catOptions);
                $('.trAnime').each(function(){
                    var aurl = $.absoluteLink($(this).find('.aAnime').attr('href'));
                    con.log(dbSelector+'/'+$.titleToDbKey($.urlAnimeTitle($.urlAnimeIdent(aurl)))+'/bdid',$(this).find('.aCategory').attr('bdid'));
                    GM_setValue(dbSelector+'/'+$.titleToDbKey($.urlAnimeTitle($.urlAnimeIdent(aurl)))+'/bdid',$(this).find('.aCategory').attr('bdid'));
                });
            }else{
                var bdid = GM_getValue( dbSelector+'/'+$.titleToDbKey($.urlAnimeTitle($.urlAnimeIdent($.normalUrl())))+'/bdid', null);
                if(bdid != null){
                    $('#spanBookmarkManager').after('&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a class="aCategory" href="#" onclick="return false;" title="Move to other folder"><img border="0" style="vertical-align:middle" src="/Content/Images/folder.png"> Folder</a>');
                    $('.aCategory').click(function () {
                        $(this).hide();
                        var aCat= $(this);
                        $(this).after(GM_getValue(dbSelector+'catOptions',""));
                        $('body').on('change', '.selectCats', function() {
                            var element  = $(this);
                            var strUncate = ' Uncategorized';
                            var categoryName = $(this).val();
                            if (categoryName == ''){return;}
                            if (categoryName == strUncate)
                                categoryName = "";
                            $.ajax({
                                type: "POST",
                                url: "/ChangeBookmarkCategory",
                                data: "bdid=" + bdid + "&category=" + categoryName,
                                success: function (message) {
                                    if (message != "!error!") {
                                        element.remove();
                                        aCat.show();
                                    }
                                    else {
                                        element.html("<option value=''>Error!</option>");
                                    }
                                }
                            });
                        });
                    });
                }
            }
        });
    }
    //##############################
    //#####Calls######
    if(window.location.href.indexOf("/BookmarkList") > -1 ){
        $.docReady(function() {
            var optionsTarget = $("#divEmailNotify");
            if(malBookmarks == 1){
                var check = 'checked';
            }else{
                var check = '';
            }
            if(BookmarksStyle == 1 && malBookmarks == 1){
                var checkfix = 'checked';
                $('.bigBarContainer').before('<div id="rightside" style="margin-right: 100px;"><div class="rightBox"> <div class="barTitle">Options</div> <div class="barContent"> <div class="arrow-general"> &nbsp;</div> <div id="optionsTarget"> </div> </div> </div></div>');
                optionsTarget = $("#optionsTarget");
                $('.bigBarContainer>.barContent>div>div:not([class])').first().remove();
            }else{
                var checkfix = '';
            }
            if(classicBookmarks == 1 && malBookmarks == 1){
                var checkClassic = 'checked';
            }else{
                var checkClassic = '';
            }
            optionsTarget.bookmarkButton(check);//optionsTarget.before('<div><input type="checkbox" id="malBookmarks" '+check+' > MyAnimeList Bookmarks</div><div class="clear2">&nbsp;</div>');
            $('#malBookmarks').change(function(){
                if($('#malBookmarks').is(":checked")){
                    malBookmarks = 1;
                    GM_setValue('malBookmarks', 1);
                    location.reload();
                }else{
                    malBookmarks = 0;
                    GM_setValue('malBookmarks', 0);
                    location.reload();
                }
            });
            if(malBookmarks == 1){
                optionsTarget.classicBookmarkButton(checkClassic);//optionsTarget.before('<div><input type="checkbox" id="BookmarksStyle" '+checkfix+' > Fix Bookmark styling</div><div class="clear2">&nbsp;</div>');
                $('#classicBookmarks').change(function(){
                    if($('#classicBookmarks').is(":checked")){
                        classicBookmarks = 1;
                        GM_setValue('classicBookmarks', 1);
                        location.reload();
                    }else{
                        classicBookmarks = 0;
                        GM_setValue('classicBookmarks', 0);
                        location.reload();
                    }
                });
            }
            var flashpos = $('body');
            flashpos.prepend('<div style="text-align: center;position: fixed;bottom:10px;width:100%;z-index: 100000;left: 0;"><div id="flash" style="display:none;  background-color: red;padding: 20px; margin: 0 auto;max-width: 60%;          -webkit-border-radius: 20px;-moz-border-radius: 20px;border-radius: 20px;background:rgba(227,0,0,0.6);                       "></div></div>');
        });
        if(malBookmarks == 1){
            try{
                GM_addStyle(bookmarkCss);
                if(BookmarksStyle == 1){
                    GM_addStyle(bookmarkFixCss);
                }
                if(classicBookmarks == 1){
                    GM_addStyle('.listing tr:not(.head) br{display: none;} .listing tr:not(.head) .title{width: 30%; float: left;padding-bottom: 0 !important;}.kissData { width: 35% !important;} .MalData {width: 35% !important;}td.Timage {height: 0 !important;} #cssTableSet{min-width: 0 !important} #endSpacer{width: 0 !important;}');
                    GM_addStyle('select.malStatus { width: 33% !important; float: left; margin-right: 9%;}select.malUserRating {width: 33% !important; float: left;}.malEpisode {width: 25%; float: left;}');
                }
            }catch(e){}

            getMalXml();
        }
    }else if(window.location.href.indexOf("myanimelist.net") > -1 ){
        setKissToMal();
    }else{
        $("head").click(function() {
            checkdata();
        });

        checkdata();
        window.onpopstate = function (event) {
            checkdata();
        };
    }


})();

/**
 * External Script
 * author Remy Sharp
 * url http://remysharp.com/2009/01/26/element-in-view-event-plugin/
 */
(function ($) {
    function getViewportHeight() {
        var height = window.innerHeight; // Safari, Opera
        var mode = document.compatMode;

        if ( (mode || !$.support.boxModel) ) { // IE, Gecko
            height = (mode == 'CSS1Compat') ?
            document.documentElement.clientHeight : // Standards
            document.body.clientHeight; // Quirks
        }

        return height;
    }

    $(window).scroll(function () {
        var vpH = getViewportHeight() + 500,
            scrolltop = (document.documentElement.scrollTop ?
                document.documentElement.scrollTop :
                document.body.scrollTop),
            elems = [];
        
        $.each($.cache, function () {
            if (this.events && this.events.inview) {
                elems.push(this.handle.elem);
            }
        });

        if (elems.length) {
            $(elems).each(function () {
                if ($(this).css("display") != "none") {
                    var $el = $(this),
                        top = $el.offset().top,
                        height = $el.height(),
                        inview = $el.data('inview') || false;

                    if (scrolltop > (top + height) || scrolltop + vpH < top) {
                        if (inview) {
                            $el.data('inview', false);
                            $el.trigger('inview', [ false ]);                        
                        }
                    } else if (scrolltop < (top + height)) {
                        if (!inview) {
                            $el.data('inview', true);
                            $el.trigger('inview', [ true ]);
                        }
                    }
                }
            });
        }
    });
    
    $(function () {
        $(window).scroll();
    });
})(jQuery);
长期地址
遇到问题?请前往 GitHub 提 Issues,或加Q群1031348184

赞助商

Fishcpy

广告

Rainyun

注册一下就行

Rainyun

一年攒够 12 元