function randomizeUrlForAjax(url){
	if(url.indexOf('?')>0){
		url = url + '&';
	}else{
		url = url + '?';
	}
	url = url + '_=' + (Math.random());
	return url;
}

function evaluateSourceForRemoteLink(source,$link){
	eval(source);
}
function evaluateSourceForRemoteForm(source,$form){
	eval(source);
}

function remote_link(l){
	$that = $(l);
	if($that.hasClass("confirm") && !confirm("Opravdu?")){
		return false;
	}
	// existuje nejaka alternativni callback fce pro remote_link?
	if (typeof before_remote_link != "undefined") {
			// ano. spustme ji...
			var ret = before_remote_link($that);
			if (ret !== null) {
					// before_remote_link vykonala nejakou akci, koncime
					return ret;
			}
			// before_remote_link vratilo null, coz znamena, ze ma 
			// byt provedena originalni akce (viz nize)
	}
	$('body').css('cursor','wait');
	var method = 'GET';
	var data = undefined;
	if($that.hasClass("remote_post_link")){
		method = 'POST';
		data = ''; // Toto vynuti nastaveni hlavicky Content-Length: 0
	}
	$.ajax({
		$link: $that,
		cache: false,
		type: method,
		data: data,
		url: $that.attr('href'),
		dataType: 'text',
		complete: function(){
			$('body').css('cursor','default');
		},
		success: function(source){
			evaluateSourceForRemoteLink(source,this.$link);
			// existuje nejaka alternativni callback fce pro remote_link?
			if (typeof after_remote_link != "undefined") {
					// ano. spustme ji...
					after_remote_link(this.$link);
			}
		}
	});
	$that.blur();
	return false;
}

var remote_form = function(f){
	$that = $(f);
	$('body').css('cursor','wait');
	$.ajax({
		$form: $that,
		cache: false,
		type: 'POST',
		url: randomizeUrlForAjax($that.attr('action')),
		dataType: 'text',
		data: $that.serialize(),
		complete: function(){
			$('body').css('cursor','default');
		},
		success: function(source){
			evaluateSourceForRemoteForm(source,this.$form);
		}
	});
	return false;
}

$(function(){
	$('a.remote_link, a.remote_post_link').click(function(){ return remote_link(this); });
	$('form.remote_form').submit(function(){ return remote_form(this); });
});

