
var KH = {}

KH.DialogMgr = {
	dialogs: [],
	
	show: function (name, cb) {
		alert('show');
		$('.kh-dialog').hide();
		$('.kh-dialog .errors').empty();
		$('.kh-dialog').center().hide().show('normal');
		
		KH.Dialog.callback = cb;
	},
	
	get: function (name) {
		if (!this.dialogs[name]) {
			this.dialogs[name] = new KH.Dialog(name);
		}
		return this.dialogs[name];
	}
};

/** DIALOG **/
KH.Dialog = function (id) {
	var main = this;
	
	this.id = id;
	
	var dlg = $('#'+id);
	var dlgForm = dlg.find('form');
	
	dlg.find('.kh-dialog-body').prepend('<div class="errors"></div>');
	
	$(document.body).append(dlg);
	
	var test = $('.kh-dialog form');
	
	dlg.append(
		"<div class='kh-dialog-bar'>"
		//+ "<button class='kh-dialog-ok' type='submit'>OK</button>"
		+ "<button class='kh-dialog-cancel'>Cancel</button>"
		+ "</div>"
	);
	
	$('.kh-dialog-bar .kh-dialog-cancel').click(function (ev) {
		main.hide();
	});
	$('.kh-dialog-bar .kh-dialog-ok').click(function (ev) {
		alert('clicked ok');
		if (main.onsubmit) main.onsubmit();
		dlgForm.submit();
	});
	
	// configure form
	dlgForm.ajaxForm({
		beforeSubmit: function () {
			KH.applyMask(dlg, 'Processing...');
		},
		success: function (response) {
			KH.removeMask(dlg);
			
			if (response.success) {
				main.hide();

				if (main.callback) main.callback();
			} else {
				dlg.find('.errors').empty();
				var errors = "";
				for (var i in response.errors) {
					errors += "<div>"+response.errors[i]+"</div>";
				}
				dlg.find('.errors').append(errors);
			}		
		},
		dataType: 'json'
	});
}
KH.Dialog.prototype.show = function () {
	// hide all dialogs
	$('.kh-dialog').hide('fast');
	
	// show this one
	$('#'+this.id).center().hide().show('normal');
}
KH.Dialog.prototype.hide = function () {
	var dlg = $('#'+this.id);
	KH.removeMask(dlg);
	dlg.hide('normal');
	dlg.find('form').resetForm();
	dlg.find('.errors').empty();
}
KH.Dialog.prototype.oncomplete = function (f) {
	this.callback = f;
}

/** MASK **/
KH.applyMask = function (div, label) {
	$(div).append('<div class="kh-mask"></div>');
	$(div).append('<div class="kh-mask-title"><div>' + label + '</div></div>');
	$(div).find('.kh-mask').show();
	$(div).find('.kh-mask-title').show();
}
KH.removeMask = function (div) {
	$(div).children('.kh-mask').remove();
	$(div).children('.kh-mask-title').remove();
}
