function parse_result(json_str){
	var json;
	try{
		json=JSON.parse(json_str);
	}
	catch(e){
		alert("Cannot parse JSON.\n\n"+json_str);
		return false;
	}
	if(json.status=="success"){
		alert(json.message);
		return json;
	}
	else if(json.status=="error"){
		alert(json.message+"\n\n"+json.file+":"+json.line);
		return false;
	}
	else{
		alert("Cannot retrieve status.\n\n"+json_str);
		return false;
	}
}

function ajax_send_form(form,callback){
	var post=[];
	for(i=0;i<form.elements.length;i++){
		if(["TEXT","TEXTAREA","PASSWORD","HIDDEN","EMAIL"].indexOf(form.elements[i].type.toUpperCase())>=0){
			post.push(form.elements[i].name+"="+encodeURIComponent(form.elements[i].value));
		}
		else if(["CHECKBOX","RADIO"].indexOf(form.elements[i].type.toUpperCase())>=0){
			if(form.elements[i].checked) post.push(form.elements[i].name+"="+encodeURIComponent(form.elements[i].value));
		}
		else if(["SELECT","SELECT-ONE","SELECT-MULTIPLE"].indexOf(form.elements[i].type.toUpperCase())>=0){
			for(var j=0;j<form.elements[i].options.length;j++){
				if(form.elements[i].options[j].selected) post.push(form.elements[i].name+"="+encodeURIComponent(form.elements[i].options[j].value));
			}
		}
	}
	post=post.join("&");
	var xhr=new XMLHttpRequest();
	xhr.open("POST",form.action);
	xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
	xhr.onreadystatechange=function(){if(xhr.readyState==4){
		var json;
		if(json=parse_result(xhr.responseText)){
			if(callback) callback(json);
		}
	}}
	xhr.send(post);
}

function ajax_send(url,callback){
	refresh=typeof(refresh)!='undefined'?refresh:true;
	var xhr=new XMLHttpRequest();
	xhr.open("GET",url);
	xhr.onreadystatechange=function(){if(xhr.readyState==4){
		var json;
		if(json=parse_result(xhr.responseText)){
			if(callback) callback(json);
		}
	}}
	xhr.send();
}

function add_onload(func){
	var oldonload = window.onload;
	if (typeof window.onload != 'function') {
		window.onload = func;
	} else {
		window.onload = function() {
			if (oldonload) {
				oldonload();
			}
			func();
		}
	}
}

