/**
 * Handler for the save button. Data is saved by opening a window
 * (as hidden as possible) pointing to the save servlet. The checkSaveWin
 * is used to check the window while waiting for the response. If saving
 * is successful, the window will be closed. If something goes wrong,
 * the window remains and the error message can be extracted from the
 * window's source.
 */

function FileSaver(formHolder) {
	this.formHolder = formHolder;
	this.saveWin = false
}

/** Open the save window. */
FileSaver.prototype.saveFile = function() {
	if (this.saveWin) {
		try { this.saveWin.close(); } catch (err) {}
	}
	this.saveWin = open(this.formHolder.getFormName() + '.wkd?form=' + this.formHolder.getFormName(),'','width=1,height=1,top=10000,left=10000,directories=no,location=no,menubar=no,scrollbars=no,status=no,titlebar=no,toolbar=no');
	delayedCall(this.saveWin, ".close()", 10000);
	this.checkSaveWin();
}

/**
 * Check the save window.
 * If the window is closed, do nothing.
 * If the window is empty, call this function again.
 * If there is content in the window, an error has occurred.
 */
FileSaver.prototype.checkSaveWin = function() {
	try {
		if (this.saveWin.document) { // Is the window still open?
			if (this.saveWin.document.body == null || this.saveWin.document.body.innerHTML == '') {
				// The window hasn't got any content yet.
				delayedCall(this, '.checkSaveWin()', 10);
			} else {
				// There is content. An error has occurred.
				var resultHTML = this.saveWin.document.body.innerHTML;
				this.saveWin.close();
				var index = resultHTML.search(/[\d][\d][\d]/);
				var index2 = resultHTML.indexOf('</', index);
				var errorCode = resultHTML.substr(index, 3);
				var errorMsg = resultHTML.substring(index+6, index2);
				if (errorMsg == 'sessiontimeout') {
					sessionTimeoutEvent.timeout.fire();
				} else {
					showMessage(errorMsg);
				}
			}
		}
	} catch (err) {}
}

