var note_data = [];
note_data['1-2'] = 'note # 2';
note_data['1-7'] = 'this is 7';

var note = {by_mid:1, about_mid:2, focus:false, last_length:0};
var is_down = false;
function $(id) { return document.getElementById(id); }

function addEvent(node, type, listener)
{
	if (node.addEventListener) {
		// standard
		node.addEventListener(type, listener, false);
	} else if (node.attachEvent) {
		// IE
		node['e'+type+listener] = listener;
		node[type+listener] = function() {
			node['e'+type+listener](window.event);
		}
		node.attachEvent('on'+type, node[type+listener]);
	}
}

function removeEvent(node, type, listener)
{
	if (node.removeEventListener) {
		// standard
		node.removeEventListener(type, listener, false);
	} else if (node.detachEvent) {
		// IE
		node.detachEvent('on'+type, node[type+listener]);
		node[type+listener] = null;
	}
}

addEvent(window, 'load', function() {
	// page loaded
	addEvent($('title-bar'), 'mousedown', function(e) {
		if (is_down) { return; }
		is_down = true;
		
		note.pos = get_mouse_coords(e);
		note.origin = get_position($('note-window'));
		addEvent(document, 'mousemove', mouseMove);
		addEvent(document, 'mouseup', function(e) {
			removeEvent(document, 'mousemove', mouseMove);
			set_pad_opacity(100);
			is_down = false;
		});
		set_pad_opacity(50);
	});
	
	addEvent($('dragger'), 'mousedown', function(e) {
		if (is_down) { return; }
		is_down = true;
		
		note.pos = get_mouse_coords(e);
		note.width = $('note-window').offsetWidth;
		note.height = $('note-window').offsetHeight;
		note.origin = get_position($('dragger'));
		addEvent(document, 'mousemove', dragMove);
		addEvent(document, 'mouseup', function(e) {
			removeEvent(document, 'mousemove', dragMove);
			set_pad_opacity(100);
			is_down = false;
		});
		if (e && e.stopPropagation != null) {
			e.stopPropagation();
			e.preventDefault();
		}
		return false;
	});
	
	addEvent($('close'), 'mouseover', function(e) { $('close').src = '/notes/close-icon-hover.gif'; });
	addEvent($('close'), 'mouseout', function(e) { $('close').src = '/notes/close-icon.gif'; });
	addEvent($('close'), 'click', function(e) {
		save_note();
		close_note();
	});
	
	addEvent($('pad-area'), 'focus', function(e) {
		note.focus = true;
	});

	addEvent($('pad-area'), 'blur', function(e) {
		save_note();
		note.focus = false;
	});
	
	//$('title-bar').focus();
	
	setInterval("notepad_tick()", 500);
});

function mouseMove(e)
{
	var pos = get_mouse_coords(e);
	var dx = note.pos.x - pos.x;
	var dy = note.pos.y - pos.y;
	
	set_position($('note-window'), note.origin.x - dx, note.origin.y - dy);
}

function dragMove(e)
{
	var pos = get_mouse_coords(e);
	var dx = note.pos.x - pos.x;
	var dy = note.pos.y - pos.y;
	var w = note.width - dx;
	var h = note.height - dy - 15;
	
	w = w<150 ? 150 : w;
	h = h<150 ? 150 : h;
	with($('note-window').style) {
		width = (w) + 'px';
		height = (h+15) + 'px';
	}
	$('pad-area').style.height = (h-15)+'px';
}

function set_position(el, x, y)
{
	el.style.top = y + 'px';
	el.style.left = x + 'px';
}

function set_pad_opacity(p)
{
	$('rest').style.opacity = p / 100;
	$('rest').style.filter = 'alpha(opacity='+p+')';
	$('rest').style.width = '100%';  // IE workaround
}

function get_mouse_coords(e)
{
	var posx = 0;
	var posy = 0;
	if (!e) var e = window.event;
	if (e.pageX || e.pageY) 	{
		posx = e.pageX;
		posy = e.pageY;
	}
	else if (e.clientX || e.clientY) 	{
		posx = e.clientX + document.body.scrollLeft
			+ document.documentElement.scrollLeft;
		posy = e.clientY + document.body.scrollTop
			+ document.documentElement.scrollTop;
	}
	return {x:posx, y:posy};
}

function get_position(el)
{
	var x=0, y=0;
	
	do {
		x += el.offsetLeft || 0;
		y += el.offsetTop || 0;
		el = el.offsetParent;
		
		if (el) {
			if (el.tagName.toUpperCase() == 'BODY') break;
			if (getStyle(el, 'position') !== 'static') break;
		} 
	} while (el);
	return {x:x, y:y};
}

function getStyle(el,styleProp)
{
	if (el.currentStyle)
		var y = el.currentStyle[styleProp];
	else if (window.getComputedStyle)
		var y = document.defaultView.getComputedStyle(el,null).getPropertyValue(styleProp);
	return y;
}

function debug(msg) { $('debug-area').innerHTML += msg + '<br/>'; }

// when dragging an image IE will not send mousemove events because of the default drag behavior
document.ondragstart = function(e) { return false; }

addEvent(document, 'keydown', function(e) {
	if (!note.focus) return;
	note.last_activity = new Date().getTime();
	note.dirty = true;
});

function notepad_tick(e)
{
	var t = new Date().getTime();
	var note_length = $('pad-area').innerHTML.length;
	
	if (note_length != note.last_length) {
		note.dirty = true;
		note.last_length = note_length;
		note.last_activity = t;
	}
	
	if (!note.last_activity) return;
	if ( (t - note.last_activity) > 2000 && note.dirty ) {
		save_note();
	}
}

function save_note()
{
	if (!note.dirty) return;
	note.dirty = false;
	var req = getXMLHTTPRequest();
	
	req.open("POST", "/notes/save_note.php", true);
	req.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
	req.send("by_mid="+note.by_mid+"&about_mid="+note.about_mid+"&note="+$('pad-area').innerHTML);
	var note_id = get_note_id();
	note_data[note_id] = $('pad-area').innerHTML;
	
	var txt = $('pad-area').innerHTML;
	if (txt && txt.length>0 && txt!='<br>') {
		$('note_'+note.about_mid).src = '/notes/note_edit.gif';
	}
}

function close_note()
{
	save_note();
	$('note-window').style.display = 'none';
	//$('note-show').style.display = 'block';
}

function getXMLHTTPRequest() {
	try { return new XMLHttpRequest(); } catch(e) {}
	try { return new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) {}
	try { return new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) {}
	alert("XMLHttpRequest not supported");
	return null;
}

function show_note(by_mid, about_mid, el)
{
	note.by_mid = by_mid;
	note.about_mid = about_mid;
	
	$('note-window').style.display = 'block';
	//note.icon.style.display = 'none';
	
	var loc = get_position(el);
	set_position($('note-window'), loc.x, loc.y);
	
	var note_id = get_note_id();
	
	// check to see if the note is already cached
	if (note_data[note_id]) {
		$('pad-area').innerHTML = note_data[note_id].replace(/&tick;/g, "'");
	} else {
		var req = getXMLHTTPRequest();
		req.open("GET", "/notes/load_note.php?by_mid="+note.by_mid+"&about_mid="+note.about_mid, false);
		req.send(null);
		$('pad-area').innerHTML = req.responseText.replace(/&tick;/g, "'");
	}
	
	note.last_length = $('pad-area').innerHTML.length; 
	$('pad-area').focus();
}

function get_note_id() { return note.by_mid + '-' + note.about_mid; }

