// ==UserScript==
// @name           GTA SnP Preview
// @namespace      http://www.samutz.com
// @description    Displays a box with basic save info when hovering over a gtasnp.com link
// @include        http://www.gtaforums.com/*
// @include        http://gtaforums.com/*
// ==/UserScript==

// Add jQuery
var SNP_JQ = document.createElement('script');
SNP_JQ.src = 'http://gtasnp.com/templates/userscript/jquery.min.js';
SNP_JQ.type = 'text/javascript';
document.getElementsByTagName('head')[0].appendChild(SNP_JQ);

// Add CSS used for tooltips
var SNP_CSS = document.createElement('link');
SNP_CSS.href = 'http://gtasnp.com/templates/userscript/tooltip.css';
SNP_CSS.rel = 'stylesheet';
SNP_CSS.type = 'text/css';
document.getElementsByTagName('head')[0].appendChild(SNP_CSS);

//Check if jQuery's loaded
function SNP_wait() {
	if(typeof unsafeWindow.jQuery == 'undefined') { window.setTimeout(SNP_wait,100); }
	else { $ = unsafeWindow.jQuery; letsJQuery(); }
}
SNP_wait();

// let's do eet!
function letsJQuery() {
	$.noConflict();
	
	// create tooltip placeholder
	$('body').append('<div id="snp_tooltip"></div>');
	
	var snp_tt_id = 0;
	var snp_tt_active = 0;
	
	// close tooltip on clicking close link
	$('#snp_tooltip').click(function(){
		$('#snp_tooltip').hide();
		snp_tt_status = 0;
	});
	
	// find gtasnp.com links
	$("a[href*='gtasnp.com']").each(function (i) {
		this.snp_tt_id++;
		var snp_regex = new RegExp('(\\d+)$', "gi");
		var snp_url = $(this).attr('href');
		var snp_id = snp_url.match(snp_regex);
		
		$(this).mouseover(function(e){
			if (snp_tt_active!=this.snp_tt_id) {
				snp_tt_active = this.snp_tt_id;
				$('#snp_tooltip').html('<img src="http://gtasnp.com/templates/images/ajax-loader.gif">');
				// $('#snp_tooltip').load('http://gtasnp.com/userscript.php?id='+snp_id);
				// .load doesn't work in GM, have to use GM_xmlhttpRequest
				setTimeout(function(){
					GM_xmlhttpRequest({
						url: 'http://gtasnp.com/userscript.php?id='+snp_id,
						method: 'GET',
						onload: function (response){
							$('#snp_tooltip').html(response.responseText);
						}
					});
				}, 0);	
				$('#snp_tooltip').css({'left': e.pageX+5, 'top': e.pageY+5});
				$('#snp_tooltip').show();
			}
		});
	});

}