// JavaScript Document
var link_title = '';
var link_url = '';

$(function() {
	
	//cache selector
	var images = $("#content img.share")
	
		
		//make images draggable
		images.draggable({
		//create draggable helper
		helper: function() {
			link_title = $(this).parent().attr("title");
			link_url   = $(this).parent().attr("href");
			return $("<div>").attr("id", "helper").html("<span>" + link_title + "</span><img id='thumb' src='" + $(this).attr("src") + "'>").appendTo("body");
		},
		cursor: "pointer",
		cursorAt: { left: -20, top: -20 },
		zIndex: 99999,
		//show overlay and targets
		start: function() {
			var IE6 = $.browser.msie && $.browser.version.substr(0,1) == 6 && !window.XMLHttpRequest
			$("<div>").attr("id", "overlay").css({ 'opacity' : 0.7 , 'background-color' : '#000' }).appendTo("body");
			if (IE6) {
				$("div#overlay").css({ 'height': $(document).height() , 'position':'absolute' });	
			}
			$("#tip").remove();
			$(this).unbind("mouseenter");
			$("#targets").css("left", ($("body").width() / 2) - $("#targets").width() / 2);
			$("#targets").css("top", $(document).scrollTop()+200);
			$("#targets").slideDown();
	
		},
		//remove targets and overlay
		stop: function() {
			$("#targets").slideUp();
			$(".share_on", "#targets").remove();
			$("#overlay").remove();
			$(this).bind("mouseenter", createTip);
		}
	});

	//make targets droppable
	$("#targets li").droppable({
		tolerance: "pointer",
		// show info when over target
		over: function() {
			$(".share_on", "#targets").remove();
			$("<div>").addClass("share_on").text("Share on " + $(this).attr("id")).addClass("active").appendTo($(this)).fadeIn();
		},
		drop: function() {
			var id     = $(this).attr("id"),
			baseUrl    = $(this).find("a").attr("href");
			link_title = encodeURI(link_title);
			if (id.indexOf("twitter") != -1) {
				var query = "/home?status=" + link_title + ": " + link_url;
			} else if (id.indexOf("delicious") != -1) {
				var query = "/save?url=" + link_url + "&title=" + link_title;
			} else if (id.indexOf("facebook") != -1) {
				var query = "/sharer.php?u=" + link_url + "&t=" + link_title;
			}
			url(baseUrl+query,true);
		}		  
	});

	var createTip = function(e) {
		//create tool tip if it doesn't exist
		($("#tip").length === 0) ? $("<div>").html("<span>Drag this to share <\/span><span class='arrow'><\/span>").attr("id", "tip").css({ left:e.pageX - 70, top:e.pageY - 50, opacity:0.7 }).appendTo("body").fadeIn(500) : null;
	};

	images.bind("mouseenter", createTip);

	// move tooltip
	images.mousemove(function(e) {
		$("#tip").css({ left:e.pageX - 70, top:e.pageY - 50 });
	});

	// remove tooltip
	images.mouseleave(function() {
		$("#tip").remove();
	});
	
});
