// Autor Jan Obrátil <jobratil@ontran.com>, Ontran Consulting www.ontran.cz 

// globální ajaxoidní akce při volání URL přes AJAX
Ajax.Responders.register(
{
	onCreate: function() 
	{
		if($('busy_box')) 
		{
			$('busy_box').show();
		}
		document.body.setStyle({ cursor : 'wait'});
	},
	onComplete: function() 
	{
		if($('busy_box')) 
		{
			$('busy_box').hide();
		}
		document.body.setStyle({ cursor : 'auto'});
	}
});

// vyrobí ajaxovou akci
function ajaxRequest(url, params) {

	new Ajax.Request(url, { 
		method: 'post',
		parameters: params,
		onSuccess: 
			function (transport) 
			{
				if(transport.responseText.isJSON() == true)
				{
					//alert(transport.responseText);
					var json = transport.responseText.evalJSON();
					var i;
					for(i=0;i<json.numOfInstructions;i++)
					{
						// alert("Provádím instrukci: " + json.instructions[i].type);
						if(json.instructions[i].type == 'js')
						{
							//alert(json.instructions[i].content);
							eval(json.instructions[i].content);
							
						} 
						else
						{
							alert("Unsupported type of action: " + json.instructions[i].type);
						}
						// alert("provedeno " + (i+1)+" z "+json.numOfInstructions);
					}
				}
				else
				{
					if(confirm("Na stránce došlo k chybě. Stránka si vyžádala ze serveru JSON objekt, ale obdržela něco jiného. \nMám zobrazit tento nevalidní obsah?"))
					{
						document.body.insert({top: "<div id='error_fixed' style='position: fixed; left: 10px; top: 10px; width: 800px; height: 400px; overflow: scroll; background-color: grey; border: 3px solid red;'><a href='#' onclick='$(\"error_fixed\").remove(); return(false);'>close</a><br />" + transport.responseText.escapeHTML() + "</div>"});
						
						return false;
					}
				}
			}
	});

}

// pro odeslání formu
function ajaxFormRequest(element_id, url) {
	if($(element_id)) {
		ajaxRequest(url, $(element_id).serialize(true));
	} 
	else {
		alert(element_id + ' neexistuje.');
	}
	
}
