// Useful dialogs for Logician (tm)
//  Copyright (c) 2008 Micah Ferrill

var input = null;

// renders a top bar for a dialog
function renderDialog(dialog){
	roundElement(dialog,{'corners':'top','color':'#999','bgColor':'#ccc','compact':'true'});
	dialog.style.background = '#fff url('.concat(getElement('bar').src,') repeat-x;')
	return dialog;
}

// displays a dialog in center screen
function showDialog(dialog,onFinish){

	// render more fully
	dialog = renderDialog(dialog);

	// insert into the currently hidden overlay
	appendChildNodes('overlay',dialog);

	// reveal the overlay
	showElement('overlay');
	
	// show the dialog
	grow(dialog, {'duration':0.5});
	
	// ensure onFinish is callable
	if (onFinish == null){
		onFinish = noop;
	}
	
	// and disable the rest of the interface temporarily
	appear('background',{'duration':0.5,'to':0.25,'afterFinish':onFinish});
}

// removes the active dialog
function hideDialog(e,callback){

	// hide and remove the dialog
	shrink('dialog',{'duration':0.5,'afterFinish':partial(removeElement,'dialog')});
	
	// hide the background and overlay
	multiple(Array('background','overlay'),fade,{'duration':0.5,'afterFinish':function(){if (callback != null){callback()}}});
}

// overrides the standard confirm dialog to stay within our window
function confirm(s,callback){

	// display a dialog
	showDialog(DIV({'id':'dialog','style':'display:none;'},
		P(null,s),
		BUTTON({'onclick':partial(hideDialog,null,callback)},'Yes'),
		BUTTON({'onclick':hideDialog},'No')
	));
}

// replaces the standard message box
function alert(s){
	showDialog(DIV({'id':'dialog','style':'display:none;'},
		P(s),
		BUTTON({'onclick':hideDialog},'Ok')
	));
}

// takes in large pieces of text
function textInput(s,callback){
	showDialog(DIV({'id':'dialog','style':'display:none;'},
		P(s),
		TEXTAREA(),
		BUTTON({'onclick':partial(finishInput,null,callback)},'Ok'),
		BUTTON({'onclick':finishInput},'Cancel')
	));
}

// implements returning textInput values
function finishInput(e,callback){

	// callback must be callable
	if (callback == null){
		callback = noop;
	}

	// get the resulting text
	var result = getFirstElementByTagAndClassName('textarea',null,'dialog').value;
	
	// hide the dialog and attach the result to the callback
	hideDialog(null,partial(callback,result));
}