/*
 * PrettyDigg 0.1.1
 * Copyright (c) 2008 Jacob Seidelin, cupboy@gmail.com, http://blog.nihilogic.dk/
 * MIT License [http://www.opensource.org/licenses/mit-license.php]
 */


var Digg = (function() {

	var iCallCount = 0;

	var strAPIKey = "";

	var bProxy = true;

	function sendRequest(strEndpoint, oContent, fncCallback) {
		iCallCount++;

		var strURL = "http://" + 
			(bProxy ? ("digg.com/tools/services?endPoint=" + encodeURIComponent(strEndpoint) + "&") : ("services.digg.com" + strEndpoint + "/?"))
			+ "type=javascript"
			+ "&appkey=" + encodeURIComponent(strAPIKey)
			+ "&callback=" + encodeURIComponent("__Digg_Callback_" + iCallCount);
			+ "&time=" + new Date().getTime();

		if (oContent) {
			for (var a in oContent) {
				if (oContent.hasOwnProperty(a)) {
					strURL += "&" + a + "=" + encodeURIComponent(oContent[a]);
				}
			}
		}

		var oScript = document.createElement("script");
		var iThisCall = iCallCount;

		var fncDigg = function(oResponse) {
			document.body.removeChild(oScript);
			if (fncCallback)
				fncCallback(oResponse);

			window["__Digg_Callback_" + iThisCall] = null;
		}

		window["__Digg_Callback_" + iThisCall] = fncDigg;

		oScript.setAttribute("type", "text/javascript");
		document.body.appendChild(oScript);
		oScript.src = strURL;
	}

	return {

		setAPIKey : function(strKey) {
			strAPIKey = strKey;
		},

		callMethod : function(strMethod, oContent, fncCallback) {
			sendRequest(strMethod, oContent, fncCallback);
		}

	}

})();



// onContent load event handling by Andrea Giammarchi 
function onContent(f){//(C)webreflection.blogspot.com
  var a=onContent,b=navigator.userAgent,d=document,w=window,c="onContent",e="addEventListener",o="opera",r="readyState",
  s="<scr".concat("ipt defer src='//:' on",r,"change='if(this.",r,"==\"complete\"){this.parentNode.removeChild(this);",c,".",c,"()}'></scr","ipt>");
  a[c]=(function(o){return function(){a[c]=function(){};for(a=arguments.callee;!a.done;a.done=1)f(o?o():o)}})(a[c]);
  if(d[e])d[e]("DOMContentLoaded",a[c],false);
  if(/WebKit|Khtml/i.test(b)||(w[o]&&parseInt(w[o].version())<9))(function(){/loaded|complete/.test(d[r])?a[c]():setTimeout(arguments.callee,1)})();
  else if(/MSIE/i.test(b))d.write(s);
};


(function() {
	var $ = function(id) {return document.getElementById(id);};

	var timers = [];
	var urls = [];
	var buttonCount = 0;

	function addEvent(element, ev, handler) 
	{
		if (element.addEventListener) { 
			element.addEventListener(ev, handler, false); 
		} else if (element.attachEvent) { 
			element.attachEvent("on" + ev, handler); 
		}
	}

	var pageLoaded = false;
	var queue = [];
	function onContentLoad() {
		pageLoaded = true;
		var button;
		while (button=queue.shift()) {
			createDiggButton(button[0],button[1]);
		}
	}

	onContent(onContentLoad);

	function createDiggButton(container, options) {
		if (!container) return false;

		options = options || {};

		var style = options.style || "default";
		var newWin = !!options.newWindow;
		var autoUpdate = !!options.autoUpdate;
		var updateInterval = Math.max(5000, options.updateInterval || 30000);
		var onlyIfDugg = !!options.onlyIfDugg;
		var onlyIfDiggUser = !!options.onlyIfDiggUser;

		var btnIdx = buttonCount;

		var html = "";
		html += "<span id='db_" + btnIdx + "' class='db_container_" + style + "' style='display:none;'>";
		html += "<a href='#' id='db_diggs_link_" + btnIdx + "' class='db_diggs_link_" + style + "' " + (newWin ? "target='_blank' " : "") + ">"
		html += "<span id='db_diggs_" + btnIdx + "' class='db_diggs_" + style + "'>";
		html += "</span>";
		html += "</a>";
		html += "</span>";

		container.innerHTML += html;

		if (!onlyIfDugg && (!onlyIfDiggUser || isDiggUser())) {
			try {
				$("db_"+btnIdx).style.display = "-moz-inline-stack";
			} catch(e) {}

			$("db_"+btnIdx).style.display = "inline-block";
		}

		buttonCount++;

		var url = options.url || window.location.href;

		if (!urls[url]) {
			urls[url] = [];
		}
		urls[url].push( {
			idx : btnIdx,
			options : options
		} );

		function onStoryFound(url, res) {
			if (urls[url]) {

				for (var i=0;i<urls[url].length;i++) {
					var btnIdx = urls[url][i].idx;
					var options = urls[url][i].options;
					var submitText = (typeof options.submitText == "string") ? options.submitText : "Digg";

					var topic = options.topic;
					var desc = options.description;
					var title = options.title;
					var media = options.media;

					var onlyIfDugg = !!options.onlyIfDugg;
					var onlyIfDiggUser = !!options.onlyIfDiggUser;

					var style = options.style || "default";

					var stories = res.stories;
					var dugg = false;
					if (stories && stories[0]) {
						dugg = true;
						var story = stories[0];
						var diggs = story.diggs;
						var storyId = story.id;
						var href = story.href;
		
						var diggTxt = "<span class='db_diggs_text_" + style + "'> diggs</span>";
						$("db_diggs_"+btnIdx).innerHTML = diggs + diggTxt;
						var link = $("db_diggs_link_"+btnIdx);
						link.setAttribute("href", href);
						link.setAttribute("title", "Digg this story! (" + diggs + " digg" + (diggs!=1 ? "s" : "") + ")");
		
					} else {
						var submitUrl = "http://digg.com/submit?"
							+ "url=" + encodeURIComponent(url) 
							+ (topic ? "&topic=" + encodeURIComponent(topic) : "")
							+ (title ? "&title=" + encodeURIComponent(title) : "")
							+ (media ? "&media=" + encodeURIComponent(media) : "")
							+ (desc ? "&bodytext=" + encodeURIComponent(desc) : "");
		
						$("db_diggs_"+btnIdx).innerHTML = "<span class='db_submit_" + style + "'>" + submitText + "</span>";
						var link = $("db_diggs_link_"+btnIdx);
						link.setAttribute("href", submitUrl);
						link.setAttribute("title", "Submit this story to Digg!");
					}
					if ((dugg || !onlyIfDugg) && (!onlyIfDiggUser || isDiggUser())) {
						try {
							$("db_"+btnIdx).style.display = "-moz-inline-stack";
						} catch(e) {}
						$("db_"+btnIdx).style.display = "inline-block";
					}
				}
			}
		}

		if (autoUpdate) {
			if (!timers[url]) {
				timers[url] = setInterval(
					function() {
						Digg.callMethod("/stories", {"link" : url}, 
							function(res) {
								onStoryFound(url, res);
							}
						);
					}, updateInterval
				)
			}
		}
		Digg.callMethod("/stories", {"link" : url}, 
			function(res) {
				onStoryFound(url, res);
			}
		);
	}
	
	Digg.createButton = function(container, options) {
		if (pageLoaded) {
			createDiggButton(container, options);
		} else {
			queue.push(
				[container, options]
			);
		}
	}

	// adapted from Jeremiah Grossman's CSS history spy code: http://jeremiahgrossman.blogspot.com/2006/08/i-know-where-youve-been.html
	var wasDiggUser;
	function isDiggUser() {
		if (document.defaultView && document.defaultView.getComputedStyle) {
			if (typeof wasDiggUser != "boolean") {
				var sites = ["http://www.digg.com/", "http://digg.com/"];
				for (var i=0;i<sites.length;i++) {          
	
					document.write('<style>');
					document.write('#idu_link_'+i+":visited {color: #FF0000;}");
					document.write('</style>');
	
					var link = document.createElement("a");
					link.id = "idu_link_"+i;
					link.setAttribute("href", sites[i]);
					link.innerHTML = sites[i];
					document.body.appendChild(link);
					var color = document.defaultView.getComputedStyle(link,null).getPropertyValue("color");
					document.body.removeChild(link);
	
					if (color == "rgb(255, 0, 0)") {
						wasDiggUser = true;
						return wasDiggUser;
					}
				}
				wasDiggUser = false;
				return wasDiggUser;
			} else {
				return wasDiggUser;
			}
		} else {
			return true;
		}
	}

})();

