
function refreshStickies(showBox)
{
	//BT:  Needed to add to prevent refresh stickie from processing when page loads.
	//	Behavior that occured was the following:  Page loads, Tool Bar displays
	//	page is redirected to login page.  
	if(ShmoopUser_auth == true)
	{
		var params = 'item_id='+ShmoopObject_id;
		params += '&item_subject='+encodeURIComponent(ShmoopObject_genus);
		params += '&item_section='+encodeURIComponent(ShmoopObject_type);
	
		if(ShmoopObject_fx != undefined)
			params += '&item_fx='+encodeURIComponent(ShmoopObject_fx);
		
		var url = '/ajax/Stickies?' + params;
		
		var xhrcall = new Ajax(url, {onComplete:AjaxResponseMap.forwardResponse});
		AjaxResponseMap.mapRequest(xhrcall, finishRefreshingStickies, window);

		if (typeof(showBox) == 'boolean' && showBox == true) {
			$('ModalWindow_CreateStickies').style.display = 'block';
		}
	
		xhrcall.request();
	}
}

window.addEvent('load', refreshStickies);

function finishRefreshingStickies(_response)
{
	if(_response.match(/no\smember/i))
	{
		// server probably timed out our session, clean up by calling signout() then login again
		signout();
		MOOdalBox.open("javascript:display_auth_panel(false, 'refreshStickies(true)')", "", "");
	}
	else if(_response != 'error')
	{
		// expecting to evaluate an array of stickies called ss	
		eval(_response);
		var c = document.getElementById('stick_container');
		for(var i=0; i<ss.length; ++i)
		{
			// throw response into empty dom element to force parse
			var el = document.createElement('span');
			el.innerHTML = decodeURIComponent(ss[i]);
			el = el.firstChild;
			var f = false;
			
			// check for stickie existence, update only if found
			for(var j=0; j<c.childNodes.length; j++)
			{
				if(c.childNodes[j].id == el.id)
				{
					c.replaceChild(el, c.childNodes[j]);
					f = true;
					break;
				} 
			}
			
			// if stickie is not found (new), add
			if(!f)
				c.appendChild(el);
			
			AutoSaveStickie.mapStickie(el.id);
		}
	}
}

function newStickie()
{
	if(document.getElementById('stick_container').style.display != 'none')
	{
		var params = 'item_id='+ShmoopObject_id;
		params += '&item_subject='+encodeURIComponent(ShmoopObject_genus);
		params += '&item_section='+encodeURIComponent(ShmoopObject_type);
		
		if(ShmoopObject_fx != undefined)
			params += '&item_fx='+encodeURIComponent(ShmoopObject_fx);
		
		var url = '/ajax/NewStickie?' + params;
			
		var xhrcall = new Ajax(url, {onComplete:AjaxResponseMap.forwardResponse});
		AjaxResponseMap.mapRequest(xhrcall, finishNewStickie, window);
		
		xhrcall.request();
	}
}

function finishNewStickie(_response)
{
	if(_response.match(/no\smember/i))
	{
		// server probably timed out our session, clean up by calling signout() then login again
		signout();
		MOOdalBox.open("javascript:display_auth_panel(false, 'newStickie()')", "", "");
	} else if(_response != 'error' && _response != 'incomplete')
	{
		// throw response into empty dom element to force parse
		var el = document.createElement('span');
		el.innerHTML = decodeURIComponent(eval(_response));
		var con = document.getElementById('stick_container');
		con.appendChild(el.firstChild);
		el = con.lastChild;
		
		// position relative to scroll
		var dim = GetWindowDimensions();
		var topval = parseInt(el.style.top) + dim.scrollY;
		el.style.top = topval + 'px';
		
		AutoSaveStickie.mapStickie(el.id);
		// adjustment for bubbles over save button on stickie
		var to = (topval - 20) + 'px';
		var lo = (parseInt(el.style.left) + 15) + 'px';
		ShowFoldersDialogue(el.id, 'stickie', lo, to);
	}

}

function updateMyFoldersDropdown() 
{
	var url = '/ajax/myFoldersDropdown';
	var xhrcall = new Ajax(url, {onComplete:AjaxResponseMap.forwardResponse});
	AjaxResponseMap.mapRequest(xhrcall, finishUpdateMyFoldersDropdown, window);

	xhrcall.request();
}

function finishUpdateMyFoldersDropdown(_response) 
{
	if(_response.match(/no\smember/i))
	{
		// server probably timed out our session, clean up by calling signout() then login again
		signout();
		MOOdalBox.open("javascript:display_auth_panel(false, 'updateMyFoldersDropdown()')", "", "");

		return;
	}

	if (document.getElementById('ModalWindow_ChooseFolder_Select').length > 0) {
		document.getElementById('ModalWindow_ChooseFolder_Select').length = 0;
	}

	if (_response != 'error' && _response != 'NO FOLDER') {
		opts = eval('(' + _response + ')');
		for (i in opts) {
			new_opt = document.createElement("option");
			new_opt.value = i;
			new_opt.text = opts[i];
			try { 
				$('ModalWindow_ChooseFolder_Select').add(new_opt);
			} catch(ex) {
				$('ModalWindow_ChooseFolder_Select').add(new_opt, null);
			}
		}
	}

	if ($('ModalWindow_ChooseFolder_Select').length > 1) {
		$('ModalWindow_CreateFolder').style.display = 'none';
		$('ModalWindow_ChooseFolder').style.display = 'block';
	}
}

function saveStickie(_id)
{
	var el = document.getElementById(_id);
	var bin = document.getElementById(_id+'_input');
	
	if(bin.value != '')
	{
		var params = 'body='+encodeURIComponent(bin.value);
		params += '&px='+parseInt(el.style.left);
		params += '&py='+parseInt(el.style.top);
		params += '&enc='+el.id;
		
		var url = '/ajax/SaveStickie?' + params;
		
		document.getElementById(_id+'_saving').innerHTML='Saving...';
		
		var xhrcall = new Ajax(url, {onComplete:AjaxResponseMap.forwardResponse});
		// Map ajax response to stickie element for execution in element's context
		AjaxResponseMap.mapRequest(xhrcall, finishSavingStickie, el);

		xhrcall.request();
	}
}

function finishSavingStickie(_response)
{
	if(_response.match(/ok=.+/))
	{
		setTimeout('document.getElementById("'+this.id+'_saving").innerHTML="Saved at '+currentTime()+'"', 1000);
		AutoSaveStickie.mapStickie(this.id);
	}
	else if(_response.match(/no\smember/i))
	{
		// server probably timed out our session, clean up by calling signout() then login again.
		// Let the user re-engage the function he wants instead of going on directly after login.
		// This is not too smooth but it's probably not worth to implement direct function handling
		// as passing parameter is not too easy.
		signout();
		MOOdalBox.open("javascript:display_auth_panel(false, ' ')", "", "");
	}
}

function confirmDeleteStickie(_id)
{
	var _el = document.getElementById(_id);
	// left offset of 32: 300 (stickie width) - 235 (delete width) / 2
	var lo = parseInt(_el.style.left)+32;
	ShowDeleteDialogue('Stickie', deleteStickie, enableStickieControls, _id, lo+'px', _el.style.top);
	disableStickieControls(_id);
}

function disableStickieControls(_id)
{
	document.getElementById(_id+'_controls').style.visibility = 'hidden';
}

function enableStickieControls(_id)
{
	document.getElementById(_id+'_controls').style.visibility = 'visible';
}

function deleteStickie(_id)
{
	var _el = document.getElementById(_id);
	var params = 'enc='+_el.id;
	
	var url = '/ajax/DeleteStickie?' + params;
	
	var xhrcall = new Ajax(url, {onComplete:AjaxResponseMap.forwardResponse});
	// Map ajax response to stickie element for execution in element's context
	AjaxResponseMap.mapRequest(xhrcall, finishDeletingStickie, _el);

	xhrcall.request();
}

function finishDeletingStickie(_response)
{
	if(_response.match(/ok=[0-9a-zA-Z]+/i))
		this.parentNode.removeChild(this);
	else if(_response.match(/no\smember/i))
	{
		// server probably timed out our session, clean up by calling signout() then login again
		// Let the user re-engage the function he wants instead of going on directly after login.
		// This is not too smooth but it's probably not worth to implement direct function handling
		// as passing parameter is not too easy.
		signout();
		MOOdalBox.open("javascript:display_auth_panel(false, ' ')", "", "");
	}
}

function updateStickiePosition(_el)
{
	if(_el.id != 'stick_new')
	{
		var params = 'enc=' + _el.id;
		params += '&px=' + parseInt(_el.style.left);
		params += '&py=' + parseInt(_el.style.top);
		
		var url = '/ajax/SaveStickie?' + params;
		
		var xhrcall = new Ajax(url, {onComplete:AjaxResponseMap.forwardResponse});
		// Map ajax response to stickie element for execution in element's context
		AjaxResponseMap.mapRequest(xhrcall, finishUpdatingStickiePosition, _el);

		xhrcall.request();
	}
}

function finishUpdatingStickiePosition(_response)
{
	if(_response.match(/no\smember/i))
	{
		// server probably timed out our session, clean up by calling signout() then login again
		// Let the user re-engage the function he wants instead of going on directly after login.
		// This is not too smooth but it's probably not worth to implement direct function handling
		// as passing parameter is not too easy.
		signout();
		MOOdalBox.open("javascript:display_auth_panel(false, ' ')", "", "");
	}
}

function bringToTop(_el)
{
	var container = document.getElementById('stick_container');
	if(container.lastChild != _el)
	{
		container.removeChild(_el);
		container.appendChild(_el);
	}
}

function focusOnInput(_e, _id)
{
	DragStickie.dontdrag(_e);
	var el = document.getElementById(_id);
	AutoSaveStickie.activeStickie(el)
	bringToTop(el);
	showInputState(_id);
}

function blurOnInput(_e, _id)
{
	AutoSaveStickie.scheduleSave(true);
	hideInputState(_id);
}

function showInputState(_id)
{
	var bin = document.getElementById(_id+'_input');
	if(bin.className != 'stickies_field')
	{
		bin.className = 'stickies_field';
		bin.parentNode.className = 'stickies_field_wrapper';
	}
	bin.focus();
}

function hideInputState(_id)
{
	var bin = document.getElementById(_id+'_input');
	if(bin.className != 'stickies_no_field')
	{
		bin.className = 'stickies_no_field';
		bin.parentNode.className = 'stickies_no_field_wrapper';
	}
}

function showAllStickies()
{
	var container = document.getElementById('stick_container');
	for(var i=0; i<container.childNodes.length; ++i)
		container.childNodes[i].style.display = 'block';
	container.style.display = 'block';
	document.getElementById('img_show_all_stickies').src = '/media/07_2008/toolbar/stickies/at/show_all.gif';
	document.getElementById('img_hide_all_stickies').src = '/media/07_2008/toolbar/stickies/un/hide_all.gif';
}

function hideAllStickies()
{
	document.getElementById('stick_container').style.display = 'none';
	document.getElementById('img_show_all_stickies').src = '/media/07_2008/toolbar/stickies/un/show_all.gif';
	document.getElementById('img_hide_all_stickies').src = '/media/07_2008/toolbar/stickies/at/hide_all.gif';
}

function _DragStickie()
{
	this.aEl = null;
	this.lx = 0;
	this.ly = 0;
	this.dty = false;
	
	EventMap.mapEvent('onload', function() {
		EventMap.mapEvent('onmousemove', this.onmove, this, document.body);
		EventMap.mapEvent('onmouseup', this.done, this, document.body);
		EventMap.unmapEvent();
	}, this, window);
}

function removeAllStickies()
{
	var container = $('stick_container');
	var total_children = container.childNodes.length;
	for (var i = 0; i < total_children; i++) {
		container.removeChild(container.firstChild);
	}
}

_DragStickie.prototype.onmove = function(e) {
	if(this.aEl != null)
	{
		var dx = e.x - this.lx;
		var dy = e.y - this.ly;
		this.aEl.style.top = (parseInt(this.aEl.style.top) + dy) + 'px';
		this.aEl.style.left = (parseInt(this.aEl.style.left) + dx) + 'px';
		
		if(this.dx != 0 || this.dy != 0)
		{
			this.dty = true;
//			if(window.ie)
//				document.selection.clear();
//			else
//				window.getSelection().removeAllRanges();
		}
	}
	this.lx = e.x;
	this.ly = e.y;
};

_DragStickie.prototype.makeDraggable = function(_el) {
	this.aEl = _el;
	
	if(window.Preview)
		window.Preview.lock = true;
};

_DragStickie.prototype.done = function(e) {
	if(this.aEl != null)
	{
		if(this.dty)
		{
			updateStickiePosition(this.aEl);
			if(window.ie)
				document.selection.clear();
			else
				window.getSelection().removeAllRanges();
		}
			
		if(window.Preview)
			window.Preview.lock = false;

		this.aEl = null;
		this.dty = false;
	}
};

_DragStickie.prototype.dontdrag = function(e) {
	if(!e)
		var me = new Event(window.event);
	else
		var me = new Event(e);
	me.stopPropagation();
}

var DragStickie = new _DragStickie();


function _AutoSaveStickie()
{
	this.lvm = {};
	this.ae = false;
	this.tid = false;
}

_AutoSaveStickie.prototype.mapStickie = function(_id)
{
	var tEl = document.getElementById(_id+'_input');
	// add last value to map
	var f = false;
	for(var i in this.lvm)
	{
		if(i == _id)
		{
			this.lvm[i] = tEl.value;
			f = true;
			break;
		}
	}
	
	// if element id not found in value map
	if(!f)
	{
		// add to map
		this.lvm[_id] = tEl.value;
		
		// set events
		EventMap.mapEvent('onkeyup', this.scheduleSave, this, tEl);
	}
}

_AutoSaveStickie.prototype.activeStickie = function(_el)
{
	this.ae = _el;
}

_AutoSaveStickie.prototype.deactiveStickie = function()
{
	this.ae = false;
}

_AutoSaveStickie.prototype.scheduleSave = function(_override)
{
	if(this.ae)
	{
		var tEl = document.getElementById(this.ae.id+'_input');
		for(var i in this.lvm)
		{
			if(i == this.ae.id && this.lvm[i] != tEl.value)
			{
				if(this.tid)
					clearTimeout(this.tid)

				if(_override == true)
					saveStickie(this.ae.id);
				else
					this.tid = setTimeout('saveStickie(\''+this.ae.id+'\')', 2000);
			}
		}
	}
}

var AutoSaveStickie = new _AutoSaveStickie();
