Crazycatz00 / Gelbooru Additions

// ==UserScript==
// @name		Gelbooru Additions
// @description Common tag button; Try to show deleted posts; Auto-select wiki entries
// @namespace	Crazycatz00
// @match		*://gelbooru.com/*
//  addTagButton-only support for:
// @match		*://danbooru.donmai.us/*
// @match		*://chan.sankakucomplex.com/*
// @match		*://yande.re/*
// @version		2.1.0
// @icon		http://gelbooru.com/favicon.png
// @grant		none
// ==/UserScript==

(function(){'use strict';
	var TAG_BUTTON_ADD = JSON.parse(localStorage.gm_ga_tags || '[]'),

	_addNotice = (function(){
		var prev;
		return function(d){
			var notice = document.createElement('div'), i;
			notice.className = 'status-notice';
			if(d.id){notice.id = d.id;}
			if(d.brand !== false){notice.textContent = 'Gelbooru Additions: ';}
			
			if(!(d.c instanceof Array)){d.c = [d.c];}
			for(i = 0; i < d.c.length; ++i){
				if(d.c[i] instanceof HTMLElement){notice.appendChild(d.c[i]);}
				else{notice.appendChild(document.createTextNode(d.c[i]));}
			}
			
			if(!prev){
				if((i = document.getElementsByClassName('status-notice')).length > 0){
					prev = i[i.length - 1];
				}
				else if(((i = document.getElementById('content')) && (i = i.previousSibling)) || (i = document.getElementById('header'))){
					prev = i;
				}
				else{prev = document.body.firstChild;}
			}
			return (prev = prev.parentNode.insertBefore(notice, prev.nextSibling));
		};
	}()),
	_makeLink = function(t, u, c){
		var a = document.createElement('a');
		a.textContent = t;
		a.href = u || '#';
		if(typeof c === 'function'){a.addEventListener('click', c, false);}
		return a;
	},
	
	// Add a button to add user-defined "default" tags to the search.
	// Does not add duplicates, and can detect tag negates (cat vs -cat).
	addTagButton = function(){
		var tgt = document.getElementById('tags');
		if(tgt){
			if(window.location.hostname === 'gelbooru.com'){
				document.head.appendChild(document.createElement('style')).textContent = 'input.secondary_search.gm_txtbtn{font:bold 11px verdana,sans-serif;color:#fff;background:#3a5ae4;}input.secondary_search.gm_txtbtn:hover{background:#e49f1e;}';
			}
			var inp = document.createElement('input');
			inp.type = 'button';
			inp.className = 'secondary_search gm_txtbtn';
			inp.value = 'Add User Tags';
			inp.title = TAG_BUTTON_ADD.join(' ') || '[None]';
			inp.addEventListener('click', function(e){
				if((e || window.event).ctrlKey || TAG_BUTTON_ADD.length === 0){
					e = prompt('User Tags', TAG_BUTTON_ADD.join(' '));
					if(typeof e === 'string'){
						inp.title = e || '[None]';
						TAG_BUTTON_ADD = e.split(' ').filter(function(t){return t.length !== 0;});
						if(TAG_BUTTON_ADD.length > 0){
							localStorage.gm_ga_tags = JSON.stringify(TAG_BUTTON_ADD);
						}else{
							localStorage.removeItem('gm_ga_tags');
						}
					}
				}else{
					TAG_BUTTON_ADD.forEach(function(t){
						var tag = t[0] === '-' ? t.substr(1) : t;
						if(typeof tag === 'string' && tag.length > 0 && this.value.search(new RegExp('(?:^|\\s)[-~]?' + tag + '(?:\\s|$)', 'i')) === -1){
							this.value += ' ' + t;
						}
					}, tgt);
				}
			}, false);
			tgt.parentNode.insertBefore(inp, tgt.nextSibling);
		}
	},
	// Try to show deleted posts as transparently as possible. Can handle resize preferences.
	postView_deletedViewer = function(){
		var deleted = Array.prototype.filter.call(document.querySelectorAll('#post-view>.status-notice'), function(e){
			e.innerHTML = e.innerHTML.replace(/(http:\/\/\S+)/, '<a href="$1">$1</a>');
			return e.textContent.search(/This\s+post\s+was\s+deleted/i) !== -1;
		}), tgt;
		if(deleted.length > 0 && (tgt = document.querySelector('#right-col>div:nth-child(2)'))){
			var img = document.createElement('img'),
				dat = window.image || {};
			img.id = 'image';
			
			if(dat.domain && dat.base_dir && dat.dir && dat.img){
				img.src = dat.domain + '/' + dat.base_dir + '/' + dat.dir + '/' + dat.img;
			}
			else if(!Array.prototype.some.call(document.querySelectorAll('.sidebar3 a[href]'), function(e){
				if(e.textContent.search(/Original\s+image/i) !== -1){
					img.src = e.href;
					_addNotice({c: ['Fallback "original" image URL used.']});
					return true;
				}
			})){
				_addNotice({c: ['Failed to find an image URL.']});
				return;
			}
			
			if(dat.sample_width > 0 && dat.sample_height > 0 && window.Cookie.get('resize-original') != 1){
				img.width = dat.sample_width * 1;
				img.height = dat.sample_height * 1;
				console.log(dat);
				if(window.Note){window.Note.sample = true;}
				if(window.Cookie.get('resize-notification') != 1){
					window.Post.highres = function(){
						img.width = img.naturalWidth || 'auto';
						img.height = img.naturalHeight || 'auto';
						if(window.Note){
							window.Note.sample = false;
							window.Note.all.invoke('adjustScale');
						}
						document.getElementById('resized_notice').style.display = 'none';
					};
					_addNotice({
						brand: false, id: 'resized_notice',
						c: [
							'This image has been resized. Click ',
							_makeLink('here', 0, window.Post.highres),
							' to view the original image. ',
							_makeLink('Always view original', 0, function(){
								window.Cookie.create('resize-original', 1);
								window.Cookie.create('resize-notification', 1);
								window.Post.highres();
							}),
							'. ',
							_makeLink('Do not show this message', 0, function(){
								window.Cookie.create('resize-notification', 1);
								document.getElementById('resized_notice').style.display = 'none';
							}),
							'.'
						]
					});
				}
			}
			
			if((window.tags instanceof Array && (dat = window.tags.join(' '))) || ((dat = document.getElementById('tags')) && (dat = dat.value))){img.alt = dat;}
			if(window.Note && typeof window.Note.toggle === 'function'){img.addEventListener('click', window.Note.toggle, false);}
			
			tgt.insertBefore(img, tgt.firstChild);
		}
	},
	// On a wiki list page, click: 1) the only entry [len == 1] 2) the entry matching what was searched [len > 1]
	wikiList_autoSelect = function(){
		var list = document.querySelectorAll('.content table td:nth-child(2)>a[href*="page=wiki"][href*="s=view"]');
		if(list.length > 1 && window.location.search.search(/[?&]search=([^&]+)(?:&|$)/) !== -1){
			list = Array.prototype.filter.call(list, function(e){return e.textContent === this;}.bind(decodeURIComponent(RegExp.$1).toLowerCase()));
		}
		if(list.length === 1){list[0].click();}
	};

	addTagButton();
	var page = window.location.search.search(/[?&]page=([^&]+)(?:&|$)/) !== -1 ? RegExp.$1 : '',
		action = window.location.search.search(/[?&]s=([^&]+)(?:&|$)/) !== -1 ? RegExp.$1 : '';
	switch(page){
		case 'wiki':
			switch(action){
				case 'list': wikiList_autoSelect();break;
			}
			break;
		case 'post':
			switch(action){
				case 'view': postView_deletedViewer();break;
			}
			break;
	}
}());