var IE = document.all?true:false
if (!IE) document.captureEvents(Event.MOUSEMOVE)
document.onmousemove = getMouseXY;

var mouseX = 0
var mouseY = 0

var links = [];

function getMouseXY(e) {
  if (IE) { // grab the x-y pos.s if browser is IE
    mouseX = event.clientX + document.body.scrollLeft
    mouseY = event.clientY + document.body.scrollTop
  } else {  // grab the x-y pos.s if browser is NS
    mouseX = e.pageX
    mouseY = e.pageY
  }  
  if (mouseX < 0){mouseX = 0}
  if (mouseY < 0){mouseY = 0}  
  return true
}

$(document).ready(function() {
	$('#win1').draggable({
		zIndex: 	60,
		ghosting:	false,
		opacity: 	0.7,
		handle:	'#win1_handle',
		cursor: 'move'
	});	

	$('.dLink').click(function()
	{
		var address = $(this).attr('href');
		var t = address.split('#');
		var id = t[1];
		getLinkContent(id);
		$("#win1").show();
		$("#win1").css("top", mouseY+10);
		$("#win1").css("left", mouseX+10);
		return false;
	});
		
	$('#win1_close').click(function()
	{
		$("#win1").hide();
		return false;
	});
	
});

function getLinkContent(id) {
	if (links[id] != undefined) {
		pasteLink(links[id]);
	} else {
		$('#link_header').html('Loading...');
		$('#win1_content').html('Please, wait..');
//		$.getJSON(DYNAMIC_LINKS_URL, {action: "get", linkId: id}, pasteLink);
		$.ajax({
			type: "GET",
			url: DYNAMIC_LINKS_URL,
			dataType: "json",
			data: {action: "get", linkId: id},
			success: pasteLink,
            error:function (xhr, ajaxOptions, thrownError){
				console.log(xhr);
				console.log(ajaxOptions);
				console.log(thrownError);
				
				$('#link_header').html("Error");
				$('#win1_content').html("An error occured");
				$("#win1").hide(3000);
			}  			
		});
	}
}

function pasteError(data) {
	$('#link_header').html("Error");
	$('#win1_content').html(data);
	toNewWindow('win1_content');
}


function pasteLink(data) {
	if (links[data.id] == undefined) {
		links[data.id] = data;
	}
	$('#link_header').html(data.text);
	$('#win1_content').html(data.description);
	toNewWindow('win1_content');
}

function toNewWindow(pid) {
	var a = document.getElementById(pid);
	if (a) { var ch = a.getElementsByTagName("a"); for (var i=0;i<ch.length;i++) ch[i].target = "_blank"; }
}	


