window.$add_class = function (o, name)
{
	o.className += " " + name;
	return o;
}

window.$remove_class = function (o, name)
{
	var names = name.split(" ");
	var changed = o.className;

	for (var i = 0; i < names.length; i++)
		changed = changed.replace(new RegExp("(^| |\t)" + names[i] + "($| |\t)", "g"), " ");

	if (changed != o.className)
		o.className = changed;
	return o;
}

window.$has_class = function (o, name)
{
	var names = name.split(" ").join("($| |\t)|(^| |\t)");
	return new RegExp("(^| |\t)" + names + "($| |\t)").test(o.className);
}

function desktop_box_toggle(toggle_link, type)
{
	var toggle_img = toggle_link.getElementsByTagName("img")[0];

	var box = toggle_link.parentNode;
	while (box && !$has_class(box, "box"))
		box = box.parentNode;

	var params = {type: type, value: 0};
	if ($has_class(box, "box-open"))
	{
		$remove_class(box, "box-open");
		$add_class(box, "box-closed");
		toggle_img.src = toggle_img.src.replace("-collapse-", "-expand-");
		params.value = 0;
	}
	else
	{
		$add_class(box, "box-open");
		$remove_class(box, "box-closed");
		toggle_img.src = toggle_img.src.replace("-expand-", "-collapse-");
		params.value = 1;
	}

	desktop_save_update("collapse", params, null, false);
	fix_height();

	return false;
}

function desktop_box_open_parent(node)
{
	var box = node;
	while (box && !$has_class(box, "box"))
		box = box.parentNode;

	if (!box)
	{
		box = node.firstChild;
		while (box && (box.tagName == "" || !$has_class(box, "box")))
			box = box.nextSibling;
	}

	if (!box || $has_class(box, "box-open"))
		return;

	var links = box.getElementsByTagName("a");
	for (var i = 0; i < links.length; i++)
	{
		if ($has_class(links[i], "box-toggle-link"))
			links[i].onclick();
	}
}

var desktop_last_options = null;
var desktop_last_privacy = null;
var desktop_last_just_open = false;
function desktop_open_options(options_link)
{
	var options = options_link;
	while (options && !$has_class(options, "options-open"))
		options = options.nextSibling;

	desktop_close_options();
	desktop_last_options = options;

	options.style.display = "block";

	desktop_last_just_open = true;
	document.body.onclick = desktop_check_close_options;

	fix_height_reflow();

	return false;
}

function desktop_open_privacy(privacy_link)
{
	var privacy = privacy_link;
	while (privacy && !$has_class(privacy, "share-open"))
		privacy = privacy.nextSibling;

	desktop_close_privacy();
	desktop_last_privacy = privacy;

	if (privacy)
		privacy.style.display = "block";

	desktop_last_just_open = true;
	document.body.onclick = desktop_check_close_options;

	fix_height_reflow();

	return false;
}

function desktop_close_options()
{
	if (desktop_last_options != null)
		desktop_last_options.style.display = "none";

	document.body.onclick = null;

	fix_height_reflow();

	return false;
}

function desktop_close_privacy()
{
	if (desktop_last_privacy != null)
		desktop_last_privacy.style.display = "none";

	document.body.onclick = null;

	fix_height_reflow();

	return false;
}

function desktop_open_cheers(options_link)
{
	var options = options_link;
	while (options && !$has_class(options, "cheers-open"))
		options = options.nextSibling;

	desktop_close_cheers();
	desktop_last_options = options;

	options.style.display = "block";

	desktop_last_just_open = true;
	document.body.onclick = desktop_check_close_options;

	fix_height_reflow();

	return false;
}

function desktop_close_cheers()
{
	if (desktop_last_options != null)
		desktop_last_options.style.display = "none";

	document.body.onclick = null;

	fix_height_reflow();

	return false;
}

var desktop_item_last_open_link = null;
var desktop_item_last_opened = null;
function desktop_item_open(link)
{
	if (desktop_item_last_opened != null)
	{
		if (!desktop_item_close(desktop_item_last_opened))
			return false;
	}

	var item = link;
	while (item && !$has_class(item.parentNode, "item-list"))
		item = item.parentNode;

	var item_open = item.nextSibling;
	while (item_open && !$has_class(item_open, "item-open"))
		item_open = item_open.nextSibling;

	item.style.display = "none";
	item_open.style.display = "block";

	desktop_item_last_open_link = link;
	desktop_item_last_opened = item_open;

	fix_height_reflow();

	var textareas = item_open.getElementsByTagName("textarea");
	for (var i = 0; i < textareas.length; i++)
	{
		if ("resize" in textareas[i])
			textareas[i].resize();
	}

	function redraw_late()
	{
		if (link.id && desktop_step_redraw)
		{
			var match = link.id.match(/-([0-9]+)$/);
			if (match && match[1])
			{
				desktop_step_redraw(match[1], "view");

				var new_hash = "";
				if (link.id.indexOf("goal") == -1)
					new_hash = "#todo" + match[1];
				else
					new_hash = "#goal" + match[1];

				if (window.location.hash != new_hash)
					window.location.hash = new_hash;
			}
		}
	}
	setTimeout(redraw_late, 0);

	item_open.resetOnCloseState = desktop_step_save_state(item_open);
	return item_open;
}

window.onbeforeunload = function ()
{
	if (!desktop_item_last_opened)
		return undefined;

	var item_open = desktop_item_last_opened;
	while (item_open && !$has_class(item_open.parentNode, "item-list"))
		item_open = item.parentNode;

	var item = item_open.previousSibling;
	while (item && !$has_class(item, "item-short"))
		item = item.previousSibling;

	var cmp_to = desktop_step_save_state(item_open);
	if (!desktop_items_locked && item_open.resetOnCloseState != false && !desktop_step_cmp_state(item_open.resetOnCloseState, cmp_to))
		return "Your changes haven't been saved yet.\nIf you continue, your changes will be lost.";
	return undefined;
}

function desktop_item_close(link)
{
	var item_open = link;
	while (item_open && !$has_class(item_open.parentNode, "item-list"))
		item_open = item.parentNode;

	var item = item_open.previousSibling;
	while (item && !$has_class(item, "item-short"))
		item = item.previousSibling;

	var cmp_to = desktop_step_save_state(item_open);
	if (item_open.resetOnCloseState != false && !desktop_step_cmp_state(item_open.resetOnCloseState, cmp_to))
	{
		if (!desktop_items_locked && !confirm("Your changes haven't been saved yet.\nIf you continue, your changes will be lost."))
			return false;

		desktop_step_restore_state(item_open.resetOnCloseState);
	}

	if (!("permanentGone" in item_open))
	{
		item.style.display = "block";
		item_open.style.display = "none";
	}

	desktop_item_last_opened = null;

	fix_height_reflow();

	return true;
}

var desktop_item_show_more_hash = false;
function desktop_item_show_more(link, params)
{
	var item = link.parentNode;
	while (item && !$has_class(item.parentNode, "item-list"))
		item = item.parentNode;

	function finish(request)
	{
		item.style.display = "none";

		var frag = document.createDocumentFragment();
		var fake = document.createElement("div");
		fake.innerHTML = request.responseText;

		var temp_list = [];
		while (fake.childNodes.length > 0)
		{
			temp_list.push(fake.childNodes[0]);
			frag.appendChild(fake.childNodes[0]);
		}
		item.parentNode.appendChild(frag);

		window.onloadQueue = [];
		for (var i = 0; i < temp_list.length; i++)
		{
			if ("getElementsByTagName" in temp_list[i])
				site_apply_scripts(temp_list[i]);
		}
		window.onload({});

		var items = item.parentNode.getElementsByTagName("li");
		for (var i = 0; i < items.length; i++)
		{
			if ($has_class(items[i], "item-more-hidden"))
			{
				items[i].style.display = "block";
				$remove_class(items[i], "item-more-hidden");
			}

			items[i].onmouseover = function ()
			{
				$add_class(this, "hover");
			}
			items[i].onmouseout = function ()
			{
				$remove_class(this, "hover");
			}
		}

		fix_height_reflow();

		if (desktop_item_show_more_hash)
			desktop_check_hash();
		desktop_item_show_more_hash = false;
	}

	desktop_save_update("draw_more", params, finish, true);
}

function desktop_check_close_options(ev)
{
	if (!ev)
		ev = window.event;
	var target = typeof(ev.target) == "undefined" ? ev.srcElement : ev.target;
	while (target && target != desktop_last_options)
		target = target.parentNode;

	if (!desktop_last_just_open && !target)
	{
		desktop_close_options();
		desktop_close_privacy();
	}
	desktop_last_just_open = false;

	return true;
}

function desktop_fixup_boxes()
{
	var lis = document.getElementsByTagName("li");
	var i;

	var total = 0;
	var single_item = null;

	var tree = {};
	var more_items = {};
	for (i = 0; i < lis.length; i++)
	{
		var parent = lis[i].parentNode;
		if (!$has_class(parent, "item-list"))
			continue;
		parent = parent.parentNode.className;

		if (!$has_class(lis[i], "item-open") && !$has_class(lis[i], "item-more"))
		{
			if (!(parent in tree))
				tree[parent] = [];
			tree[parent].push(lis[i]);

			total++;
			single_item = lis[i];
		}
		else if ($has_class(lis[i], "item-more"))
			more_items[parent] = lis[i];

		lis[i].onmouseover = function ()
		{
			$add_class(this, "hover");
		}
		lis[i].onmouseout = function ()
		{
			$remove_class(this, "hover");
		}
	}

	if (total == 1)
	{
		function open()
		{
			if (desktop_item_last_opened == null)
				desktop_item_open(single_item);
		}
		window.setTimeout(open, 150);
	}

	for (var k in tree)
	{
		if (k in more_items)
		{
			more_items[k].style.display = tree[k].length > 9 ? "block" : "none";

			var spans = more_items[k].getElementsByTagName("span");
			for (var i = 0; i < spans.length; i++)
			{
				if (!$has_class(spans[i], "item-more-count"))
					continue;

				var n = tree[k].length - 9;
				spans[i].innerHTML = (n == 1 ? "is " : "are ") + n + " more";
			}
		}

		if (tree[k].length == 1)
		{
			var open = tree[k][0];
			while (!$has_class(open, "item-open"))
				open = open.nextSibling;

			$add_class(open, "item-open-single");
		}
	}

	var content = $("site-content");
	for (i = 0; i < content.childNodes.length; i++)
	{
		if (content.childNodes[i].className == "site-left-content")
			content.childNodes[i].style.overflow = "visible";
	}

	fix_height_reflow();
}

function desktop_set_reminder(type, id, value, date)
{
	if (!date)
		date = "";

	var params = {type: type, id: id, value: value, date: date};
	desktop_save_update("reminder", params, null, true);

	if (date == "")
	{
		if ($("reminder_date_" + id))
			$("reminder_date_" + id).value = date;
	}
	else
	{
		var types = ["weekly", "daily", "monthly", "none"];
		for (var i = 0; i < types.length; i++)
		{
			var el = $("reminder_period_" + id + "_" + types[i]);
			if (el)
				el.checked = false;
		}
	}
}

function desktop_hide_box(toggle_link, type)
{
	var box = toggle_link.parentNode;
	while (box && !$has_class(box, "box"))
		box = box.parentNode;

	box.style.display = "none";

	var params = {type: type};
	desktop_save_update("hide", params, null, true);

	fix_height_reflow();
}

function desktop_save_update(func, params, finish, fail)
{
	if (!finish)
		finish = function ()
		{
		}

	if (fail === true)
		fail = function ()
		{
			alert("Unable to save your changes.  Please try again.");
			location.reload();
		}

	var vals = [];
	for (var k in params)
		vals.push(escape(k) + "=" + escape(params[k]));

	http_post(desktop_base_url + "/update.html?do=" + func, vals.join("&"), finish, fail);
}

function desktop_clear_field(id)
{
	if (typeof(id) == "string")
		id = $(id);

	if (id.style.color == "")
		return;
	id.style.color = "";
	id.value = "";
}

function desktop_delete_item(type, id)
{
	var dialog_id = "desktop-confirm-delete-" + type;
	var dialog = $(dialog_id).cloneNode(true);

	dialog.style.display = "block";
	show_overlay_content(dialog, 550);
	make_overlay_dark();

	function del_confirm()
	{
		function finish()
		{
			window.location.reload();
		}

		desktop_save_update("delete", {type: type, id: id}, finish, true);
	}

	function del_cancel()
	{
		hide_overlay_content();
	}

	var links = dialog.getElementsByTagName("a");
	for (var i = 0; i < links.length; i++)
	{
		if (links[i].className == "confirm")
			links[i].onclick = del_confirm;
		if (links[i].className == "cancel")
			links[i].onclick = del_cancel;
	}
}

var desktop_share_item_link = null;
function desktop_share_item(type, id, link)
{
	desktop_share_item_link = link;

	function finish(request)
	{
		show_overlay_content(request.responseText, 728);
		make_overlay_dark();
	}

	function fail()
	{
		alert("Unable to open the share dialog.  Please try again.");
	}

	http_post(site_url + "/desktop/share.html", "type=" + type + "&id=" + id, finish, fail);
}

function desktop_progress_open(id)
{
	function finish(request)
	{
		show_overlay_content(request.responseText, 728);
		make_overlay_dark();
	}

	function fail()
	{
		alert("Unable to open the progress.  Please try again.");
	}

	http_post(site_url + "/desktop/progress.html", "id=" + id, finish, fail);
}

function desktop_progress_close()
{
	hide_overlay_content();
}

function desktop_check_hash()
{
	var open = null;

	var m = window.location.hash.match(/^#chart([0-9]+)$/);
	if (m && m[1])
		chart_show_overlay(m[1]);

	var m = window.location.hash.match(/^#(goal|todo)([0-9]+)$/);
	if (m && m[1] && m[2])
	{
		open = $("desktop-" + m[1] + "-short-" + m[2]);

		if (!open && !desktop_item_show_more_hash)
		{
			desktop_item_show_more_hash = true;
			if ($(m[1] + "-more-link"))
				$(m[1] + "-more-link").onclick();
		}

		if (open)
			open = desktop_item_open(open);
	}

	if (open)
	{
		open.scrollIntoView();

		desktop_box_open_parent(open);
	}
}

event_queue("onload", function ()
{
	desktop_fixup_boxes();
	window.setTimeout(desktop_check_hash, 100);
});
