moshmage / SCNSRC Summary

// ==UserScript==
// @name         SCNSRC Summary
// @namespace    mosh.mage
// @version      1.0
// @description  This addin makes a summary on the right-side of scnsrc.*
// @author       MoshMage
// @include      *scnsrc.*
// @grant        none
// ==/UserScript==

(function() {
    var _$ = jQuery.noConflict(),
        debug = false,
        doc = {
            target: _$('.content'),
            posts: _$('.post', this.target),
            holder: _$('<div style="padding: 10px; position: fixed; top: 14%; right:0; width:16%; background: white;"><div class="wp-pagenavi" style="margin-top:14px; margin-bottom:14px;"><a class="toggleInt" isOpen="false" style="cursor:pointer;">Color Match</a><a class="toggleSearch search" isOpen="false" >Quick Links</a><a class="toggleRemove remove" isOpen="false" >Filter Words</a></div><ul></ul></div>').addClass('wp-mod-ts-content'),
            interactive: _$('<div style="border-top:1px solid; margin-top: 14px;"><ul></ul></div>').addClass('wp-pagenavi wp-mods'),
            buttonNewSearchTerm: _$('<a data-storage="wtsSearchTerm">new search term</a>'),
            buttonSaveSearchTerm: _$('<a data-storage="wtsSearchTerm">save search term</a>'),
            buttonSaveWord: _$('<a data-storage="wtsWordColorMatch">save words</a>'),
            buttonAddWord: _$('<a data-storage="wtsWordColorMatch">new word match</a>'),
            removeList: _$('<li><textarea class="word" placeholder="query,another query,separate,by commas"></textarea><a class="saveWord" data-storage="wtsRemoveString">save</a></li>')
        },
        hole = {
            posts: '',
            wordsList: '',
            quickList: '',
            removeList: '',
            colorBoxList: ["IndianRed","LightCoral","Salmon","DarkSalmon","LightSalmon","Crimson","Red","FireBrick","DarkRed","Pink","LightPink","HotPink","DeepPink","MediumVioletRed","PaleVioletRed","LightSalmon","Coral","Tomato","OrangeRed","DarkOrange","Orange","Gold","Yellow","LightYellow","LemonChiffon","LightGoldenrodYellow","PapayaWhip","Moccasin","PeachPuff","PaleGoldenrod","Khaki","DarkKhaki","Lavender","Thistle","Plum","Violet","Orchid","Fuchsia","Magenta","MediumOrchid","MediumPurple","Amethyst","BlueViolet","DarkViolet","DarkOrchid","DarkMagenta","Purple","Indigo","SlateBlue","DarkSlateBlue","MediumSlateBlue","GreenYellow","Chartreuse","LawnGreen","Lime","LimeGreen","PaleGreen","LightGreen","MediumSpringGreen","SpringGreen","MediumSeaGreen","SeaGreen","ForestGreen","Green","DarkGreen","YellowGreen","OliveDrab","Olive","DarkOliveGreen","MediumAquamarine","DarkSeaGreen","LightSeaGreen","DarkCyan","Teal","Aqua","Cyan","LightCyan","PaleTurquoise","Aquamarine","Turquoise","MediumTurquoise","DarkTurquoise","CadetBlue","SteelBlue","LightSteelBlue","PowderBlue","LightBlue","SkyBlue","LightSkyBlue","DeepSkyBlue","DodgerBlue","CornflowerBlue","MediumSlateBlue","RoyalBlue","Blue","MediumBlue","DarkBlue","Navy","MidnightBlue","Cornsilk","BlanchedAlmond","Bisque","NavajoWhite","Wheat","BurlyWood","Tan","RosyBrown","SandyBrown","Goldenrod","DarkGoldenrod","Peru","Chocolate","SaddleBrown","Sienna","Brown","Maroon","White","Snow","Honeydew","MintCream","Azure","AliceBlue","GhostWhite","WhiteSmoke","Seashell","Beige","OldLace","FloralWhite","Ivory","AntiqueWhite","Linen","LavenderBlush","MistyRose","Gainsboro","LightGrey","Silver","DarkGray","Gray","DimGray","LightSlateGray","SlateGray","DarkSlateGray","Black"]
        },
        defFilter = {'xvid':'red'},
        defQuick = {"https://duckduckgo.com/?q=":'D'},
        defRemove = {};
    if (!localStorage.getItem('wtsWordColorMatch')) {
        localStorage.setItem('wtsWordColorMatch',JSON.stringify(defFilter));
    }
    if (!localStorage.getItem('wtsSearchTerm')) {
        localStorage.setItem('wtsSearchTerm',JSON.stringify(defQuick));
    }
    if (!localStorage.getItem('wtsRemoveString')) {
        localStorage.setItem('wtsRemoveString',JSON.stringify(defRemove));
    }
    function createColorBox() {
    	var colorList = hole.colorBoxList,
    		str = "",color;
    	if (typeof colorList === "string") return colorList;
    	for (color in colorList) {
    		str += '<option style="background-color:'+colorList[color]+';" value="'+colorList[color]+'"><span style="color:"'+colorList[color]+'";-webkit-filter: invert(100%); filter: invert(100%)" >'+colorList[color]+'</span></option>';
    	}
    	return str;
    }
    function addColorMatch(word,color,storage) {
        if (storage === false) storage = wtsWordColorMatch;
        var filterString = (JSON.parse(localStorage[storage])) ? JSON.parse(localStorage[storage]) : {};
        if (color === false) filterString = '/'+word+'/g';
        else { filterString[word] = color; filterString = JSON.stringify(filterString); }
        localStorage.setItem(storage,filterString);
        
    }
    function wordColorMatch(sentence) {
        var filterString = JSON.parse(localStorage.wtsWordColorMatch),
            word;
        for (word in filterString) {
            if (sentence.toLowerCase().indexOf(word.toLowerCase()) >= 0) return 'color: '+filterString[word];
        }
        return 'color: black';
    }
    function quickList(pTitle) {
    	var list = JSON.parse(localStorage.wtsSearchTerm),
            str = '', quick;
        for (quick in list) {
        	if (quick) str += '<a href="'+quick+''+pTitle+'" target="_blank">'+list[quick]+'</a> ';
        }
        return str;
    }
    function applyRemoveList(title) {
    	var pattern = localStorage.wtsRemoveString.replace(/\,/g,'|');
        pattern = '('+pattern+')';
        pattern = new RegExp(pattern,"g");
    	if (!pattern) return title;
    	else {
    		title = title.replace(pattern,'');
    		return title;
    	}
    }
    function fillHole() {
        doc.posts.each(function(){
            var _this = _$(this),
                pTitle = _$('h2 a',_this).text(),
                pUrl = _this.attr('id'),
                pStyle = wordColorMatch(pTitle),
                anchors = quickList(pTitle);
			pTitle = applyRemoveList(pTitle);
            hole.posts += '<li style="text-overflow: ellipsis; white-space: nowrap; overflow: hidden">'+anchors+'<a href="#'+pUrl+'" style="'+pStyle+'" >'+pTitle+'</a><li>';
        });
    }
    function fillMods() {
        var filterString = JSON.parse(localStorage.wtsWordColorMatch),
            word,
            quickList = JSON.parse(localStorage.wtsSearchTerm);
        for (word in filterString) {
            if ((word)  && (filterString[word])) hole.wordsList += '<li style="margin-bottom:2%;"><input type=text value="'+word+'" style="width:20%; margin-right:5%;border: none;border-bottom: 1px solid grey;" class="word" /><select type=text data-value="'+filterString[word]+'" style="width:20%;border: none;border-bottom: 1px solid grey;" class="color"></select> <a class="remWord" data-word="'+word+' " style="cursor:pointer">X</a> </li>';
        }
        for (word in quickList) {
        	if ((word) && (quickList[word])) hole.quickList += '<li style="margin-bottom:2%;"><input type=text value="'+word+'" style="width:20%; margin-right:5%;border: none;border-bottom: 1px solid grey;" class="word" /><input type=text value="'+quickList[word]+'" style="width:20%;border: none;border-bottom: 1px solid grey;" class="color"/> <a class="remWord" data-word="'+word+' " style="cursor:pointer">X</a> </li>';
        }
        hole.removeList = localStorage.wtsRemoveString;
    }
    
    fillHole();
    fillMods();
    hole.colorBoxList = createColorBox();

    _$('body').append(doc.holder);
    _$(hole.posts).appendTo('.wp-mod-ts-content ul');
    _$(doc.interactive).appendTo('.wp-mod-ts-content');
    _$('#navigation .wp-pagenavi').clone(true).prependTo('.wp-mod-ts-content');

    
    doc.buttonNewSearchTerm.addClass('addWord search').appendTo('.wp-mods').toggle();
    doc.buttonSaveSearchTerm.addClass('saveWord search').appendTo('.wp-mods').toggle();
    doc.buttonSaveWord.addClass('saveWord match').appendTo('.wp-mods').toggle();
    doc.buttonAddWord.addClass('addWord match').appendTo('.wp-mods').toggle();
    
    _$(hole.wordsList).appendTo('.wp-mods ul').addClass('match').toggle();
    _$(hole.quickList).appendTo('.wp-mods ul').addClass('search').toggle();
    _$(doc.removeList).appendTo('.wp-mods ul').addClass('remove').toggle();
    _$('.wp-mods textarea').val(hole.removeList);

    _$('li.match select.color').append(hole.colorBoxList);
    _$('li.match option').each(function(){
    	var _this = _$(this),
    		value = _this.val(),
    		match = _this.parent().attr('data-value');
    	if (value === match) {
    		_this.attr('selected','true');	
    		_this.parent().attr('style','background-color:'+value);
    	} 
    });
    _$('select').change(function() {
    	var _this = _$(this),
    		color = _$(':selected',_this).val();
    	_this.attr('style','background-color:'+color);
    });

    _$('.addWord').bind("click",function() {
        var searchORmatch = (_$(this).hasClass('search')) ? 'search' : 'match',
        	str = '<li style="margin-bottom:2%;" class="'+searchORmatch+'"><input class="word" type=text value="" placeholder="Query" style="width:20%; margin-right:5%;border: none;border-bottom: 1px solid grey;" />';
        if (searchORmatch === "match") str += '<select class="color" placeholder="Color" type=text value="" style="width:20%;border: none;border-bottom: 1px solid grey;"></select> <a class="remWord" style="cursor:pointer">X</a></li>';
        else str += '<input class="color" placeholder="Color" type=text value="" style="width:20%;border: none;border-bottom: 1px solid grey;"/> <a class="remWord" style="cursor:pointer">X</a></li>';
        _$(str).appendTo('.wp-mods ul');
        if (searchORmatch === "match") _$('li select.color').append(hole.colorBoxList);
    });
    _$('.saveWord, .remWord').bind("click",function() {
        var removeParent = (_$(this).hasClass('remWord')) ? _$(this).parent().remove() : false,
            allWords = _$('.wp-mods ul li:visible'),
            storage = (_$(this).attr('data-storage'));
        localStorage.setItem(storage,"{}");	
        if (storage === "wtsRemoveString") { localStorage.setItem(storage,_$('.wp-mods textarea').val()); }
        else {
            allWords.each(function(){
                var _this = _$(this),
                    word = _$('.word',_this).val(),
                    color = (_$('.color',_this).val()) ? _$('.color',_this).val() : false;
                if (storage === "wtsWordColorMatch") color = _$('.color :selected',_this).text();
                if (color) addColorMatch(word,color,storage);
            });
        }
        
    });
    _$('.toggleInt').bind('click',function(){
        var isOpen = _$(this).attr('isOpen');
        if (isOpen === "false") { _$('.wp-mods .match').show(); _$(this).attr('isOpen','true'); }
        else { _$('.wp-mods .match').hide(); _$(this).attr('isOpen','false'); }
        _$('.wp-mods .search').hide();
        _$('.wp-mods .remove').hide();
    });
    _$('.toggleSearch').bind('click',function(){
        var isOpen = _$(this).attr('isOpen');
        if (isOpen === "false") { _$('.wp-mods .search').show(); _$(this).attr('isOpen','true'); }
        else { _$('.wp-mods .search').hide(); _$(this).attr('isOpen','false'); }
        _$('.wp-mods .match').hide();
        _$('.wp-mods .remove').hide();
    });
    _$('.toggleRemove').bind('click',function(){
        var isOpen = _$(this).attr('isOpen');
        if (isOpen === "false") { _$('.wp-mods .remove').show(); _$(this).attr('isOpen','true'); }
        else { _$('.wp-mods .remove').hide(); _$(this).attr('isOpen','false'); }
        _$('.wp-mods .match').hide();
        _$('.wp-mods .search').hide();
    });
})();