$.widget("ui.coveringnote", $.ui.dialog, {
	_dialogCreate: $.ui.dialog.prototype._create,
	_create: function() {
		var $this = this;
		this._dialogCreate();
		var height = $(window).height();
		if (height > 690) {
			height = 690;
		}
		this.option({
			title: 'Lahetteen muokkaus',
			modal: true,
			width: 430,
			height: height,
			close: function() {
				$this.clearUp();
			},
			buttons: {
				'Peruuta' : function() {
					$this.close();
				},
				'OK': function() {
					$this.submitForm();
				}
			}
		});
		$.ajax({
			url: this.options.covUrl + '/muokkaa',
			success: function(data) {
				$this.element.html(data).find('.ui-button-icon-only .ui-button-text, .ui-button-icons-only .ui-button-text').css('padding', '0.1em').find('#form-covnote').submit(function() {
					$this.submitForm();
				});
			}
		});
		this.uiDialog.find('.ui-dialog-buttonpane').append('<div style="float: left;"><a href="' + this.options.covUrl +'">Siirry kokonayttotilaan</a></div>');
	},
	submitForm: function() {
		var $this = this;
		var covForm = this.element.find('#form-covnote');
		$.ajax({
			url: covForm.attr('action'),
			type: 'POST',
			dataType: 'json',
			data: covForm.serialize(),
			success: function(data) {
				if (data.errors) {
					$('<div />').validationerrordialog({
						validationErrors: data.errors
					});
				}
				else {
					var proceed = $this._trigger('covnoteSaved');
					if (proceed !== false) {
						$this.close();
					}
				}
			}
		});
	},
	clearUp: function() {
		this.element.html('');
		this.destroy();
	}
});
