function initProjectEventHandlers() {
	$("#cloneProjectButton").live("click", function(event) {
		event.preventDefault();
		var projectId = $(event.currentTarget).attr("projectId");
		openCloneProjectDialog(projectId);
	});

	$("#shareProjectButton").live("click", function(event) {
		event.preventDefault();
		var projectId = $(event.currentTarget).attr("projectId");
		openShareProjectDialog(projectId);
	});

	$("#deleteProjectButton").live("click", function(event) {
		event.preventDefault();
		var projectId = $(event.currentTarget).attr("projectId");
		openDeleteProjectDialog(projectId);
	});

	$("#editProjectButton").live("click", function(event) {
		event.preventDefault();
		var projectId = $(event.currentTarget).attr("projectId");
		openEditProjectDialog(projectId);
	});

	$("#newProjectButton").live("click", function(event) {
		event.preventDefault();
		openNewProjectDialog();
	});

	$("#publishProjectButton").live("click", function(event) {
		event.preventDefault();
		validateProject();
		publishProject();
	});

	$("#runPrototypeButton").live("click", function(event) {
		event.preventDefault();
		var href = getRunPrototypeUrl();
		openPublishWindow(href, name);
	});

	$("#runPublishedButton").live("click", function(event) {
		event.preventDefault();
// var href = getPublishedPrototypeUrl();
		var href = getRunPrototypeUrl();
		openPublishWindow(href, name);
	});

	$("#saveUnitButton").live("click", function(event) {
		event.preventDefault();
		saveCurrentFile();
	});

	$("#generateCode").live("click", function(event) {
		event.preventDefault();
		if ("_gaq" in window) _gaq.push(['_trackEvent', 'generic', 'Generate Code']);
		var href = getGenerateCodeUrl(event.currentTarget.name);
// window.open(href, "Code");
		window.location.href = href;
	});
}

function saveCurrentFile(onSuccessCallback) {
	saveUnitSource(function() {
		validateProject(function() {
			// if mdd.properties was modified update codegen buttons, dropdown,
			// etc...
			var anchor = $("#files ul li.ui-tabs-selected a");
			var unitName = anchor.text();
			if (unitName == "mdd.properties") {
				window.location.reload();
			} else {
				updateClassNames();
				updateDiagram();
			}
		});
		
		if (onSuccessCallback) {
			onSuccessCallback.call();
		}
	});
}

function openPublishWindow(url, name) {
	name = name.replace(/^\s*|\s*$/g, ''); // remove whitespace
	if (publishWindow) {
		publishWindow.close();
	}
	publishWindow = window.open(url, name);
}

function updateValidationArea(data) {
	$("#validationArea tbody").empty(); // clear old validation
	$("#validationArea").height(0);
	// shows all kinds of problems (error, warning, info)
	var problems = $(data).find("problems");
	if (problems.size() > 0) {
		problems
				.children()
				.each(
						function() {
							var row = "<tr>";
							row = row
									+ "<td><a href='' id='goto' line='_line_' unit='_unit_'>_line_</a></td>";
							row = row
									+ "<td><a href='' id='goto' line='_line_' unit='_unit_'>_unit_</a></td>";
							row = row
									+ "<td><a href='' id='goto' line='_line_' unit='_unit_'>_description_</a></td>";
							row = row + "</tr>";
							row = row.replace(/_description_/g, $(this).attr(
									"message"));
							row = row.replace(/_unit_/g, $(this).attr("file"));
							row = row.replace(/_line_/g, $(this).attr("line"));

							$("#validationArea tbody").append(row);
						});

		$("#goto").live("click", function(event) {
			event.preventDefault();
			var unit = $(event.currentTarget).attr("unit");
			var line = $(event.currentTarget).attr("line");
			showErrorInEditor(unit, line);
		});

		$("#validationArea tbody tr:odd").addClass("odd-error");
		$(".odd-error").css("background-color",
				$(".ui-state-error").css("background-color"));
		$(".odd-error").css("background-image",
				$(".ui-state-error").css("background-image"));
		hideStatusMessage();
		showValidationArea();
	} else {
		hideValidationArea();
	}
	layoutEditProjectPage({keepWidth: true});
}

function hideValidationArea() {
	var toolbarHeight = 0;
	$("#validation-container").height(0);
	$("#validation-container").hide();
}

function showValidationArea() {
	// show the container before computing otherwise the values are incorrect
	$("#validation-container").show();
	var newHeight = $("#validationArea").outerHeight(true);
	$("#validation-container").height(newHeight);
}

function showErrorInEditor(unitName, line) {
	selectEditorTab(unitName);
	var unitId = getUnitIdFromName(unitName);
	if (unitId) {
		var editor = unitIdToEditor[unitId];
		setTimeout(function() {
			selectEditorLine(editor, line);
		}, 50);
	}
}

function selectEditorLine(editor, line) {
	var editorLine = line - 1; // 0-based
	editor.setCursor(editorLine);
}

function selectEditorTab(unitName) {
	var index = getEditorTabIndex(unitName);
	$("#files").tabs('select', index);
}

function getEditorTabIndex(unitName) {
	var anchors = $("#files ul li a");
	for (var index = 0; index < anchors.size(); index++) {
		var anchor = anchors[index];
		var text = $(anchor).text();
		if (unitName == text) {
			return index;
		}
	}
	// not found, return the first one
	return 0;
}

function getUnitIdFromName(unitName) {
	var anchors = $("#files ul li a");
	for (var index = 0; index < anchors.size(); index++) {
		var anchor = anchors[index];
		var text = $(anchor).text();
		if (unitName == text) {
			return $(anchor).attr("unitId");
		}
	}
	return undefined;
}

function initNewProjectDialog() {
	var createProjectFunction = function() {
		var name = $("#dialog-create-project #project-name").val();
		var description = $("#dialog-create-project #project-description")
				.val();
		createProject(name, description);
		return false;
	};

	$("#dialog-create-project").dialog( {
		autoOpen : false,
		modal : true,
		buttons : {
			"Cancel" : function() {
				$(this).dialog("close");
			},
			"Create" : createProjectFunction
		}
	});

	// register the submit function with the form
	$("#dialog-create-project > form:last").submit(createProjectFunction);

	// select text and focus on name field when dialog opens
	$("#dialog-create-project").bind("dialogopen", function(event, ui) {
		$("#dialog-create-project #project-creation-error").hide();
		$("#dialog-create-project #project-name").val("New Project");
		$("#dialog-create-project #project-description").val("");
		$("#dialog-create-project #project-name").select();
		$("#dialog-create-project #project-name").focus();
	});

	// styling
	$("#dialog-create-project input").addClass(
			"text ui-widget-content ui-corner-all");
	$("#dialog-create-project select").addClass(
			"text ui-widget-content ui-corner-all");
	$("#dialog-create-project textarea").addClass(
			"text ui-widget-content ui-corner-all");
}

function openNewProjectDialog() {
	canCreateProject(function() {
		$("#dialog-create-project").dialog("open");
	});
}

function showProjectCreationError(XMLHttpRequest, textStatus, errorThrown) {
	if (XMLHttpRequest.responseText) {
		// parses the text response to JSON
		eval("var status = " + XMLHttpRequest.responseText);
		$("#dialog-create-project #project-creation-error-message").html(
				status.message);
		$("#dialog-create-project #project-creation-error").show();
	}
}

function initEditProjectDialog() {
	var editProjectFunction = function() {
		var name = $("#dialog-edit-project #project-name").val();
		var description = $("#dialog-edit-project #project-description").val();
		saveProject(projectToBeEdited, name, description);
		return false;
	};

	$("#dialog-edit-project").dialog( {
		autoOpen : false,
		modal : true,
		buttons : {
			"Cancel" : function() {
				$(this).dialog("close");
			},
			"Save" : editProjectFunction
		}
	});

	// register the submit function with the form
	$("#dialog-edit-project > form:last").submit(editProjectFunction);

	// select text and focus on name field when dialog opens
	$("#dialog-edit-project").bind("dialogopen", function(event, ui) {
		$("#dialog-edit-project #project-name").select();
		$("#dialog-edit-project #project-name").focus();
	});

	// styling
	$("#dialog-edit-project input").addClass(
			"text ui-widget-content ui-corner-all");
	$("#dialog-edit-project select").addClass(
			"text ui-widget-content ui-corner-all");
	$("#dialog-edit-project textarea").addClass(
			"text ui-widget-content ui-corner-all");
}

function openEditProjectDialogWith(project) {
	$("#dialog-edit-project #edit-project-error").hide();
	$("#dialog-edit-project #project-name").val(project.name);
	$("#dialog-edit-project #project-description").val(project.description);
	$("#dialog-edit-project").dialog("open");
}

function showEditProjectError(XMLHttpRequest, textStatus, errorThrown) {
	if (XMLHttpRequest.responseText) {
		// parses the text response to JSON
		eval("var status = " + XMLHttpRequest.responseText);
		$("#dialog-edit-project #edit-project-error-message").html(
				status.message);
		$("#dialog-edit-project #edit-project-error").show();
	}
}

function initDeleteUnitDialog() {
	$("#dialog-delete-unit").dialog( {
		autoOpen : false,
		modal : true,
		buttons : {
			"Cancel" : function() {
				$(this).dialog("close");
			},
			"Delete" : function() {
				deleteUnit();
				$(this).dialog("close");
			}
		}
	});
}

function openDeleteUnitDialog(unitId) {
	if (unitId) {
		$("#dialog-delete-unit #unitId").val(unitId);
		$("#dialog-delete-unit").dialog("open");
	} else {
// console.log("openDeleteUnitDialog: missing unitId");
	}
}

function initCloneProjectDialog() {
	var cloneProjectFunction = function() {
		var name = $("#dialog-clone-project #project-name").val();
		var description = $("#dialog-clone-project #project-description").val();
		cloneProject(projectToBeCloned, name, description);
		$("#dialog-clone-project").dialog("close");
		return false;
	};

	$("#dialog-clone-project").dialog( {
		autoOpen : false,
		modal : true,
		buttons : {
			"Cancel" : function() {
				$(this).dialog("close");
			},
			"Save" : cloneProjectFunction
		}
	});

	// register the submit function with the form
	$("#dialog-clone-project > form:last").submit(cloneProjectFunction);

	// select text and focus on name field when dialog opens
	$("#dialog-clone-project").bind("dialogopen", function(event, ui) {
		$("#dialog-clone-project #project-name").select();
		$("#dialog-clone-project #project-name").focus();
	});

	// styling
	$("#dialog-clone-project input").addClass(
			"text ui-widget-content ui-corner-all");
	$("#dialog-clone-project select").addClass(
			"text ui-widget-content ui-corner-all");
	$("#dialog-clone-project textarea").addClass(
			"text ui-widget-content ui-corner-all");
}

function openCloneProjectDialogWith(project) {
	canCloneProject(function() {
		var newName = "Clone Of " + project.name;
		$("#dialog-clone-project #project-name").val(newName);
		$("#dialog-clone-project #project-description")
				.val(project.description);
		$("#dialog-clone-project").dialog("open");
	});
}

function initShareProjectDialog() {
	$("#dialog-share-project").dialog( {
		autoOpen : false,
		modal : true,
		buttons : {
			"Cancel" : function() {
				$(this).dialog("close");
			},
			"Share" : function() {
				shareProject();
			}
		}
	});
}

function openShareProjectDialog(projectId) {
	projectIdToBeShared = projectId;
	$("#dialog-share-project").dialog("open");
}

function initEditProjectPage(editing) {
	$("#newUnitButton").live("click", function(event) {
		event.preventDefault();
		openNewUnitDialog();
	});

	$("#renameUnitButton").live("click", function(event) {
		event.preventDefault();
		var selectedTab = editorTabs.tabs('option', 'selected');
		var anchor = $("#files ul li.ui-tabs-selected a");
		var unitId = anchor.attr("unitId");
		var unitName = anchor.text();
		openRenameUnitDialog(unitId, unitName);
	});

	$("#deleteUnitButton").live("click", function(event) {
		event.preventDefault();
		var selectedTab = editorTabs.tabs('option', 'selected');
		var anchor = $("#files ul li.ui-tabs-selected a");
		var unitId = anchor.attr("unitId");
		openDeleteUnitDialog(unitId);
	});

	styleButtons();

	// add a listener to create the editors only when the tab shows
	$("#files").bind("tabsshow", function(event, ui) {
		var div = ui.panel;
		createTabEditor(div, editing);
	});

	var editorTabs = createEditorTabs();
	
	// open tabs upon creation
	var $tabs = $('#files').tabs({
	    add: function(event, ui) {
			setTimeout(function() {
		        $tabs.tabs('select', '#' + ui.panel.id);
			}, 5);
	    }
	});
	
	$(".toolbar").each(function() {
		$(this).buttonset();
		$(this).css("font-size", ".7em");
	});
	
	$(".file-toolbar span").each(function() {
		$(this).css("padding", "2px 0");
	});
	
	$(".file-toolbar li").each(function() {
		$(this).css("height", "22px");
		$(this).css("width", "30px");
	});

	$(".file-toolbar li a").each(function() {
		$(this).css("height", "20px");
		$(this).css("width", "20px");
		$(this).css("padding", "1px 5px");
	});
	
	createViews();

	$(window).resize(function() {
		layoutEditProjectPage();
	});
}

function createTabEditor(node, editing) {
	var unitId = $(node).attr("unitId");
	if (unitId == undefined || unitIdToEditor.hasOwnProperty(unitId)) {
		return; // already created
	}
	var editor = createEditorFromNode(node, {
		saveFunction : saveCurrentFile,
		lineNumbers : true,
		readOnly : !editing
	});
	unitIdToEditor[unitId] = editor;
	layoutEditProjectPage({keepWidth: true});
}

function unitCreated(unit) {
	var url = "#file-" + unit.id;
	var tab = $("#files").tabs("add", url, unit.name);
	var anchor = $("#files li:last a");
	anchor.attr("unitId", unit.id);
	var div = $("#files div:last");
	div.attr("unitId", unit.id);
	div.addClass("file-area");
	createEditorTabs();
	validateProject();
}

function unitRenamed(unit) {
	var anchor = $("#files ul li.ui-tabs-selected a");
	var unitName = anchor.text(unit.name);
}

/**
 * If this is the last tab we reload the page otherwise we simply remove the
 * tab.
 */
function unitDeleted() {
	var selectedTab = $("#files").tabs('option', 'selected');
	$("#files").tabs('remove', selectedTab);
	$("#files").tabs('select', 0);
	validateProject();
}

function layoutEditProjectPage(keepWidth) {
	var width = $(window).width();
	width -= 20; // magic number
	var halfWidth = width / 2;
	
	if (keepWidth == undefined || !keepWidth) {
		$("#editor-container").width(width);
		$("#files").width(halfWidth);
		$(".CodeMirror").width(halfWidth);
		$("#views").width(halfWidth);
		$("#diagram").width(halfWidth);
	}

	var height = $(window).height();
	height -= $(".header-bg").outerHeight();
	height -= parseInt($(".header-bg").css("margin-top"));
	height -= parseInt($(".header-bg").css("margin-bottom"));
	height -= $(".app-toolbar-container").outerHeight();
	height -= parseInt($(".app-toolbar-container").css("margin-top"));
	height -= parseInt($(".app-toolbar-container").css("margin-bottom"));
	height -= parseInt($("#editor-container").css("padding-top"));
	height -= $("#validation-container").outerHeight();
	height -= parseInt($("#validation-container").css("margin-top"));
	height -= parseInt($("#validation-container").css("margin-bottom"));
	height -= 3; // magic number

	$("#editor-container").height(height);

	// left pane editors
	var editorHeight = height;
	editorHeight -= $("#files ul").outerHeight();

	$("#files").height(editorHeight);
	$("#files .CodeMirror").height(editorHeight);
	
	// views
	var viewHeight = height;
	viewHeight -= $("#views ul").outerHeight();
	$("#views").height(viewHeight);
	
	// codegen
	$("#codegen-tab").height(viewHeight);
	var codegenHeight = viewHeight;
	codegenHeight -= $("#codegen-filters").outerHeight();
	$("#codegen-preview .CodeMirror").height(codegenHeight);
	
	// diagram
	$("#diagram").height(viewHeight);
	
	// resizable
	$("#files").resizable({
		minHeight: editorHeight,
		maxHeight: editorHeight,
		handles: "e",
		resize: function(event, ui) {
			var editorWidth = $("#files").width();
			var viewWidth = width - editorWidth;
			$("#files .CodeMirror").width(editorWidth);
			$("#views").width(viewWidth);
			$("#codegen-preview .CodeMirror").width(viewWidth);
			$("#diagram").width(viewWidth);
			updateImageSize();
		},
	});
}

function initShowProjectPage() {
	styleButtons();
	createEditorTabs();

	setTimeout(function() {
		$(".source-textarea").each(function() {
			createEditor(this, {
				value : $(this).text(),
				lineNumbers : false,
				readOnly : true
			});
		});
		layoutShowProjectPage();
	}, 10);

	$(window).resize(function() {
		layoutShowProjectPage();
	});
}

function createEditorTabs() {
	var tabs = $("#files").tabs();

	$("#files").each(function() {
		$(this).css("padding", "0 0 0 5px");
		$(this).css("border", "0");
		$(this).css("background", "none");
	});

	$("#files ul").each(function() {
		$(this).css("padding", "0");
		$(this).removeClass("ui-widget-header");
	});

	$("#files li").each(function() {
		$(this).css("margin", "0");
	});

	$("#files li a").each(function() {
		$(this).css("padding-top", "0");
		$(this).css("padding-bottom", "0");
	});

	$(".file-area").each(function() {
		$(this).css("padding", "0");
		$(this).css("background-color", "white");
		$(this).css("border", "1px solid #DFD9C3");
	});

	return tabs;
}

function createViews() {
	var tabs = $("#views").tabs();

	$("#views").each(function() {
		$(this).css("padding", "0 0 0 5px");
		$(this).css("border", "0");
		$(this).css("background", "none");
	});

	$("#views ul").each(function() {
		$(this).css("padding", "0");
		$(this).removeClass("ui-widget-header");
	});

	$("#views li").each(function() {
		$(this).css("margin", "0");
	});

	$("#views li a").each(function() {
		$(this).css("padding-top", "0");
		$(this).css("padding-bottom", "0");
	});

	$(".file-area").each(function() {
		$(this).css("padding", "0");
		$(this).css("background-color", "white");
		$(this).css("border", "1px solid #CCCCCC");
		$(this).removeClass("ui-corner-bottom");
	});

	return tabs;
}

function layoutShowProjectPage() {
	var height = $(window).height();
	height -= $("#footer").outerHeight();
	height -= $("#as-layout-header").outerHeight();
	height -= $("#as-navigation").outerHeight();
	height -= parseInt($("#as-layout-content").css("padding-top"));
	height -= parseInt($("#as-layout-content").css("padding-bottom"));
	height -= parseInt($("#prototype-source-container").css("padding-top"));
	height -= 2; // what is this?

	$("#prototype-source-container").height(height);
	$("#source-container").height(height);
	$("#files").height(height);

	var textAreaHeight = height;
	textAreaHeight -= $("#files ul").outerHeight();
	textAreaHeight -= 2; // what is this?
	$(".source-textarea").height(textAreaHeight);
	$(".CodeMirror-wrapping").height(textAreaHeight);
}

function projectSaved() {
	window.location.reload();
}

function loginSuccess() {
	window.location.reload();
}

function logoutSuccess() {
	window.location.reload();
}

function initMyProjectsPage() {
	styleButtons();
}

function initSharedProjectsPage() {
	styleButtons();
}

function initPricingPage() {
	styleButtons();
}

function initContactPage() {
	styleButtons();
	$(".contact-contact a").css("color",
			$(".ui-state-default").css("background-color"));
}

function initSignUpPage() {
	styleButtons();
	$("#signup-body input").addClass("text ui-widget-content ui-corner-all");
}

function initPaymentPage() {
	styleButtons();
}

function initAccountPage() {
	$("#tabs").tabs();
	styleButtons();
	$("input").addClass("text ui-widget-content ui-corner-all");
}

function initIndexPage() {
	$(".menuButton").button();

	$("#index-diagram").hide();
	$("#index-codegen").hide();
	$("#index-prototype").hide();
	currentSlide = "#index-model";

	setInterval(function() {
		$(currentSlide).fadeOut(1000, function() {
			if (currentSlide == "#index-model") {
				currentSlide = "#index-diagram";
			} else if (currentSlide == "#index-diagram") {
				currentSlide = "#index-prototype";
			} else if (currentSlide == "#index-prototype") {
				currentSlide = "#index-codegen";				
			} else {
				currentSlide = "#index-model";
			}
			$(currentSlide).fadeIn(1000);
		});
	}, 6000);
}

function projectCreated(project) {
	showProject(project);
}

function projectCloned(project) {
	showProject(project);
}

function projectDeleted() {
	window.location.reload();
// refreshProjects();
}

function projectShared() {
	window.location.reload();
// refreshProjects();
}

function initNewUnitDialog() {
	var createUnitFunction = function() {
		var unitName = $("#dialog-create-unit #unit-name").val();
		createUnit(unitName);
		return false;
	};

	$("#dialog-create-unit").dialog( {
		autoOpen : false,
		modal : true,
		buttons : {
			"Cancel" : function() {
				$(this).dialog("close");
			},
			"Create" : createUnitFunction
		}
	});

	// register the submit function with the form
	$("#dialog-create-unit > form:last").submit(createUnitFunction);

	// select text and focus on name field when dialog opens
	$("#dialog-create-unit").bind("dialogopen", function(event, ui) {
		$("#dialog-create-unit #create-unit-error").hide();
		$("#dialog-create-unit #unit-name").val("NewFile");
		$("#dialog-create-unit #unit-name").select();
		$("#dialog-create-unit #unit-name").focus();
	});
}

function openNewUnitDialog() {
	canCreateUnit(function() {
		$("#dialog-create-unit").dialog("open");
	});
}

function showUnitCreationError(XMLHttpRequest, textStatus, errorThrown) {
	if (XMLHttpRequest.responseText) {
		// parses the text response to JSON
		eval("var status = " + XMLHttpRequest.responseText);
		$("#dialog-create-unit #create-unit-error-message")
				.html(status.message);
		$("#dialog-create-unit #create-unit-error").show();
	}
}

function initRenameUnitDialog() {
	var renameUnitFunction = function() {
		var unitId = $("#dialog-rename-unit #unitId").val();
		var unitName = $("#unit-rename").val();
		renameUnit(unitId, unitName);
		return false;
	};

	$("#dialog-rename-unit").dialog( {
		autoOpen : false,
		modal : true,
		buttons : {
			"Cancel" : function() {
				$(this).dialog("close");
			},
			"Rename" : renameUnitFunction
		}
	});

	// register the submit function with the form
	$("#dialog-rename-unit > form:last").submit(renameUnitFunction);

	// select text and focus on name field when dialog opens
	$("#dialog-rename-unit").bind("dialogopen", function(event, ui) {
		$("#dialog-rename-unit #rename-unit-error").hide();
		$("#unit-rename").select();
		$("#unit-rename").focus();
	});
}

function openRenameUnitDialog(unitId, unitName) {
	if (unitId) {
		$("#unit-rename").val(unitName);
		$("#dialog-rename-unit #unitId").val(unitId);
		$("#dialog-rename-unit").dialog("open");
	} else {
// console.log("openRenameUnitDialog: missing unitId");
	}
}

function showUnitRenameError(XMLHttpRequest, textStatus, errorThrown) {
	if (XMLHttpRequest.responseText) {
		// parses the text response to JSON
		eval("var status = " + XMLHttpRequest.responseText);
		$("#dialog-rename-unit #rename-unit-error-message")
				.html(status.message);
		$("#dialog-rename-unit #rename-unit-error").show();
	}
}

function initMain() {
	initMessageDialog();
	initLoginDialog();
	hideStatusMessage();

	// styling
	$("#logo-caption").css("color",
			$(".ui-state-default").css("background-color"));
}

function initFixedFooterLayout() {
	$('#as-layout-container').layout( {
		closable : false,
		resizable : false,
		slidable : false,
		spacing_open : 0
	});
}

function initLoginDialog() {
	var loginFunction = function() {
		var username = $("#dialog-login #username").val();
		var password = $("#dialog-login #password").val();
		login(username, password);
		return false;
	};

	$("#dialog-login").dialog( {
		autoOpen : false,
		modal : true,
		buttons : {
			"Cancel" : function() {
				$(this).dialog("close");
			},
			"Login" : loginFunction
		}
	});

	// register the submit function with the form
	$("#dialog-login > form:last").submit(loginFunction);

	$("#dialog-login").keyup(function(e) {
		if (e.keyCode == 13) {
			loginFunction();
		}
	});

	// select text and focus on name field when dialog opens
	$("#dialog-login").bind("dialogopen", function(event, ui) {
		$("#dialog-login #login-error").hide();
		$("#dialog-login #username").val("");
		$("#dialog-login #password").val("");
		$("#dialog-login #username").focus();
	});

	$("#dialog-login #login-error").hide();

	// event handlers
	$("#signinButton").live("click", function(event) {
		event.preventDefault();
		openLoginDialog();
	});

	$("#signoutButton").live("click", function(event) {
		event.preventDefault();
		logout();
	});
}

function openLoginDialog() {
	$("#dialog-login").dialog("open");
}

function showLoginError(XMLHttpRequest, textStatus, errorThrown) {
	if (XMLHttpRequest.responseText) {
		// parses the text response to JSON
		eval("var status = " + XMLHttpRequest.responseText);
		$("#dialog-login #login-error-message").html(status.message);
		$("#dialog-login #login-error").show();
	}
}

function initMessageDialog() {
	$("#dialog-message").dialog( {
		autoOpen : false,
		modal : true,
		buttons : {
			"OK" : function() {
				$(this).dialog("close");
			}
		}
	});
}

// the timeout indicates when to hide the message
function showStatusMessage(message, timeout) {
	$("#status-message").text(message);
	$("#status-message").show();
	if (timeout) {
		setTimeout(function() {
			var currentMessage = $("#status-message").text();
			if (message = currentMessage) {
				hideStatusMessage();
			}
		}, timeout);
	}
}

function hideStatusMessage() {
	$("#status-message").hide();
}

function showMessageDialog(XMLHttpRequest, textStatus, errorThrown) {
	if (XMLHttpRequest.responseText) {
		// parses the text response to JSON
		eval("var status = " + XMLHttpRequest.responseText);
		$("#dialog-message p").text(status.message);
		$("#dialog-message").dialog("open");
	}
}

function showMessageDialog2(message) {
	if (message) {
		$("#dialog-message p").text(message);
		$("#dialog-message").dialog("open");
	}
}

function styleButtons() {
	$(".menuButton").button();
	$(".toolbar").each(function() {
		$(this).buttonset();
		$(this).css("font-size", ".7em");
	});
}

function initFindDialog() {
	var lastFindTerm;
	var lastPos;
	
	var findTerm = function(next, callback) {
		var anchor = $("#files ul li.ui-tabs-selected a");
		var unitId = anchor.attr("unitId");
		if (unitId) {
			var editor = unitIdToEditor[unitId];
			var term = $("#dialog-find-editor #find-term").val();
			if (lastFindTerm != term) {
				lastPos = null;
			}
			var cursor = editor.getSearchCursor(term, lastPos || editor.getCursor());
			if (next == true) {
				if (!cursor.findNext()) {
					return;
				}
				lastPos = cursor.to();
			} else {
				if (!cursor.findPrevious()) {
					return;
				}
				lastPos = cursor.from();
			}
			editor.setSelection(cursor.from(), cursor.to());
			lastFindTerm = term;
		}
		if (callback) {
			callback.call();
		}
	}
	
	$("#dialog-find-editor").dialog( {
		autoOpen : false,
		modal : false,
		buttons : {
			"Next" : function() {
				findTerm(true);
			},
			"Previous" : function() {
				findTerm(false);
			}
		}
	});

	$("#dialog-find-editor").bind("dialogopen", function(event, ui) {
		$("#dialog-find-editor #find-error").hide();
		lastPos = null;
	});

	// styling
	$("#dialog-create-project input").addClass(
			"text ui-widget-content ui-corner-all");

	$('#dialog-find-editor').keydown(function(event) {
	    if (event.keyCode == 13) {
			event.preventDefault();
	        findTerm(true, function() {
	        	$('#dialog-find-editor #find-term').focus();
	        });
	    }
	});
	
	$(window).keydown(function(event) {
		// handle CTRL+F or COMMAND+F
		if ((event.ctrlKey || event.metaKey) && event.keyCode == 70) {
			event.preventDefault();
			openFindDialog();
		}
	});
}

function openFindDialog() {
	$("#dialog-find-editor").dialog("open");
}


