/**
	Asynchronous Form Send Engine
	@author kaine@best.net.pl
*/

var globalConfig = null;

/*
*
*
*  @param Object configObject, members:
*              - actionUrl - form action URL
*              - windowId - ID of the DOM element with form elements to send (inputs, selects, ...)
*/
function afs_send(configObject) {
	var windowDiv = document.getElementById(configObject.windowId);
	var formElement = document.createElement('FORM');
	
	formElement.setAttribute("id", "frm_" + configObject.windowId);
	
	// remove window from current position:
	windowDiv.parentNode.removeChild(windowDiv);
	
	// ... and paste it into form element:
	formElement.appendChild(windowDiv);
	formElement.style.display = 'none';
	
	// append form at the end of the body tag:
	document.body.appendChild(formElement);
	
	// creating the iframe
	var iframe = document.createElement("iframe");
	iframe.setAttribute("id", "bf_temp");
	iframe.setAttribute("name", "bf_temp");
	iframe.setAttribute("width", "0");
	iframe.setAttribute("height", "0");
	iframe.setAttribute("border", "0");
	iframe.setAttribute("style", "width: 0px; height: 0px; border: 0px;");
	
	// add to document
	formElement.parentNode.appendChild(iframe);
	window.frames['bf_temp'].name = "bf_temp"; // for IE
	
	// set the rest of the attributes:
	formElement.setAttribute("target", "bf_temp");
	formElement.setAttribute("action", configObject.actionUrl);
	formElement.setAttribute("method", "post");
	formElement.setAttribute("enctype", "multipart/form-data");
	formElement.setAttribute("encoding", "multipart/form-data");
	

	afs_addEvent(document.getElementById('bf_temp'), "load", afs_after);
	 
	globalConfig = configObject; // for OnLoad event handler
	
	var outMsg = document.getElementById('bf_temp_msg');
	outMsg.innerHTML = 'Proszę czekać <img src="' + configObject.waitImgSrc + '" width="16" height="16" />';
	
	// send form:	
	formElement.submit();
}

function afs_after() {
	var frm = document.getElementById('bf_temp');
	afs_removeEvent(frm, "load", afs_after);
	
	// get output message:
	afs_msg('bf_temp_msg');
	
	// delete iframe:
	/*
	
	setTimeout(function() { 
		frm.parentNode.removeChild(frm); 
	}, 250);
	
	*/
}

function afs_msg(elementId) {
	var outMsg = document.getElementById(elementId);
	outMsg.innerHTML = '';
	var scr = document.createElement("script");
	scr.setAttribute("type", "text/javascript");
	scr.setAttribute("charset", "utf-8");
	scr.setAttribute("src", globalConfig.messageScriptUrl);
	outMsg.appendChild(scr);
}

function afs_addEvent(object, evType, functionHandler){
	if (object.addEventListener)
		object.addEventListener(evType, functionHandler, true)
	if (object.attachEvent)
		object.attachEvent("on" + evType, functionHandler)
}

function afs_removeEvent(object, evType, functionHandler) {
	if (object.detachEvent)
		object.detachEvent('on' + evType, functionHandler);
	else
		object.removeEventListener(evType, functionHandler, false);
} 