// ==UserScript==
// @name           delicious Pecha Kucha 
// @namespace      http://www.nettpar.org.uk
// @description    Present your bookmarks on Del.icio.us
// @include        http://delicious.com/*
// ==/UserScript==

// ALL THIS CODE NEEDS A MASSIVE REFACTOR
// Add jQuery
	var cdn = new Array('http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js', 'http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/jquery-ui.min.js', 'http://ajax.googleapis.com/ajax/libs/jqueryui/1.7/themes/smoothness/jquery-ui.css');

	for (var i in cdn) {	
	  
	    lastPeriod = cdn[i].lastIndexOf('.');
		fileExt = cdn[i].slice(lastPeriod + 1);
		
		switch(fileExt)
		{
		case 'js':
		  GM_JQ = document.createElement('script');
		  GM_JQ.type = 'text/javascript';
		  GM_JQ.src = cdn[i];
		  break;
		case 'css':
		  GM_JQ = document.createElement('link');
		  GM_JQ.href = cdn[i];
		  GM_JQ.type = 'text/css';
		  GM_JQ.rel = 'stylesheet';
		  break;
		}
			    
	    document.getElementsByTagName('head')[0].appendChild(GM_JQ);
	}

// Check if jQuery's loaded
    function GM_wait() {
        if(typeof unsafeWindow.jQuery == 'undefined') { window.setTimeout(GM_wait,100); }
    else { $ = unsafeWindow.jQuery; letsJQuery(); }
    }
    GM_wait();

// API request
	function imgRequest(url, type) {
		if(url.match('http://')) {
			url = url.substring(7);
			url = url.replace(/&/,"&amp;");
		}
		//url = escape(url);
		
		if(type == 'request') {
			xml = "<webthumb><apikey>" + apikey + "</apikey><request><url>" + url + "</url></request></webthumb>";
			type = 'status';
		} else {
			xml = "<webthumb><apikey>" + apikey + "</apikey><status><url>" + url + "</url></status></webthumb>";
		}
		
		GM_xmlhttpRequest({
		    method: 'POST',
			async: false,
		    url: 'http://webthumb.bluga.net/api.php',
			data: xml,
		    onload: function(data) {
				GM_log($(data.responseText).html());
				if($(data.responseText).find("error").text() != "") {
					GM_log($(data.responseText).find("error").text());
					updatePage("ERROR");
				}
				else if($(data.responseText).find("status").text() == 'Complete') {
					pickup = $(data.responseText).find("status").attr('pickup');
					lastPeriod = pickup.lastIndexOf('.');
					imgUrl = pickup.substring(0, lastPeriod) + "-thumb_large.jpg";
					updatePage(imgUrl);
				}
				else if($(data.responseText).find("status").attr("inprocess") == 1) {
					GM_log("job is in progress")
					setTimeout(function() {
					    imgRequest(url);
					  }, 5000);
				}
				// DANGER HERE IF THE API CHANGES RESULTING IN YOU ALWAYS ENDING UP HERE.  IT WILL KEEP REQUESTING IMAGES.
				else if($(data.responseText).find("job").attr("estimate")) {
					GM_log("job was requested");
					jobtime = $(data.responseText).find("job").attr("estimate");
					updatePage("GENERATING");
					//setTimeout(function() {
					    imgRequest(url);
					  //}, jobtime * 1000);
				}
				else {
					GM_log("requesting new image");
					imgRequest(url, 'request');
				}
			}
		});
	}
	
	function updatePage(imgUrl) {
		$('#presentationdialog img, #presentationdialog h1, #presentationdialog div').remove();
		if(imgUrl == "ERROR") {
			$('#presentationdialog').prepend('<h1 style="margin-bottom:20px;">ERROR - Could not load or generate thumbnail</h1>');
		}
		else if(imgUrl == "GENERATING"){
			$('#presentationdialog').prepend('<div height="400px"><h1 style="margin-bottom:20px;">Generating a snapshot for - ' + url + '</h1><div>I\'ll just be a couple of ticks</div></div>');
		}
		else {
			$('#presentationdialog').prepend('<img src="' + imgUrl + '" style=""/>');
		}
		link = $('.taggedlink')[tagPosition];
		link = $(link).closest(".data").find(".description").text();
		$('#presentationdialog p:first').text(link);
		
		$('#next, #previous').unbind();
		if(tagPosition > 0) {
			$('#previous').replaceWith("<a id='previous' href=''>Previous</a>");
		}
		else {
			$('#previous').replaceWith("<span id='previous' style='color:gray'>Previous</span>");
		}
		
		if(tagPosition == tagSize - 1){
			$('#next').replaceWith("<span id='next' style='color:gray'>Next</span>");
		}
		else {
			$('#next').replaceWith("<a id='next' href=''>Next</a>");
		}
		
		$('#next').bind("click", function(e){
			tagPosition += 1;
			url = $('.taggedlink')[tagPosition];
			url = $(url).attr('href');
			window.setTimeout(function() {
			    imgRequest(url);
			  }, 0);
			return false;
	    });
	
		$('#previous').bind("click", function(e){
			tagPosition -= 1;
			url = $('.taggedlink')[tagPosition];
			url = $(url).attr('href');
			window.setTimeout(function() {
			    imgRequest(url);
			  }, 0);
			return false;
	    });
	}

    function letsJQuery() {
		apikey = "Paste your http://webthumb.bluga.net api key here!";
	
		$("#alt_message").append("<em>|</em> <a href='' id='pecha'>Start presentation</a>");
		elements = $('div.description');
		url = $('a.taggedlink').attr('href');
		tagSize = $('.taggedlink').length;
		tagPosition = 0;
		$("#pecha").click(function(){
			if($('#presentationdialog').length == 0) {
				$('body').after('<p id="presentationdialog"></p>');
				$('#presentationdialog').append('<p class="ui-corner-all" style="border: 1px solid gray; height:40px; text-align: left; padding: 3px;">' + "</p><p id='slidenav' style='margin-top: 5px;'><span id='previous' style='color:gray'>Previous</span> | <a id='next' href=''>Next</a></p>");
				$('#presentationdialog').dialog({height: 608, width: 700, zIndex: 5001, title: "Pecha Kucha - delicious"});
				$('#slidenav').addClass("ui-dialog-titlebar ui-widget-header ui-corner-all");
			}
			window.setTimeout(function() {
		      imgRequest(url);
		  	}, 0);
			return false;
		})
    }

