$("a.livebox-ajax").live("click", function (event) {
    event.preventDefault();
    $.get(this.href, jQuery.websystem.ajax.livebox.update);
});

jQuery.extend({
	websystem: {
		ajax: {
			livebox: {
				append: function(html) {
					$("#livebox").append(html);
				},
				update: function (payload) {
						if(payload.closeLivebox) {
							$('#livebox').dialog('close');
							jQuery.nette.success(payload);
							// reload snippets related to invalidated elements
							if(payload.invalidatedElements) {
								var data = "";
								for (var i in payload.invalidatedElements) {
									data += "invalidatedElements["+i+"]="+payload.invalidatedElements[i];
								}
								$.post(window.location.href, data);
							}

						} else if (payload.snippets) {
							jQuery.websystem.ajax.livebox.clear();
							for (var i in payload.snippets) {
								jQuery.websystem.ajax.livebox.append(payload.snippets[i]);
							}
							jQuery.websystem.ajax.livebox.show();
						}

						// redirect is not good for livebox, we just close him
						if (payload.redirect) {
							$('#livebox').dialog('close');
						}
						
						return false;
				},
				clear: function () {
					$('#livebox').html("");
				},
				close: function () {
					try{ // path for CKEDITOR
						if(CKEDITOR != undefined)
							for(editor in CKEDITOR.instances) {
								CKEDITOR.instances[editor].destroy();
							}
						}
					catch($e) {
						//alert($e);
					}

					forms_unbindKeys();
				},
				show: function() {
					$width = $('#livebox >.livebox-width').text() + 'px';
					$('#livebox').dialog({
						'autoOpen': false, // if true, box cannot be opened more them once
						'width': $width,
						'position': ['middle', 100],
						'draggable': false,
						'resizable': false,
						'modal': true,
						'beforeclose': jQuery.websystem.ajax.livebox.close
					})
					.dialog('open');

					// bind hotkeys
					forms_bindKeys();
				}
			}
		}
	}
});
