// Sends request to server and degrades nicely with no JS.
// 
// DON'T USE THIS DIRECTLY, SET UP VIA ajaxFormSetup METHOD.
function ajaxFormSubmit(ev){
	/* Prep Event and stop propagation */
	if(!ev)ev=window.event;
	xStopPropagation(ev);
	xPreventDefault(ev);
	
	var e=new xEvent(ev);
	var f=e.target;
	if(!f||f.ajaxInProgress)return;
	
	/* Assemble data */
	var meth=f.method.toUpperCase();
	var url=f.action;
	var query=null;
	for(var i=0;i<f.elements.length;i++){
		if(i>0)query+="&";
		query+=f.elements[i].name+'='+f.elements[i].value;
	}
	if(meth=='GET')url+='?'+query;
	
	/* Prepare Request */
    var req=new XMLHttpRequest();
    req.open(meth,url,true);
    req.onreadystatechange=function(){
		if(req.readyState==4){
			if(req.status==200){
				f.ajaxInProgress=false;
				var rh=f.responseHandler;
				if(rh)rh.call(this,req.responseXML,f);
			}else
				f.submit();
		}
    }
	
    /* Send the request */
	if(meth=='GET')
		req.send(null);
	else{
		req.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
		req.send(query);
	}
	
	/* Add status, which can be inspected for temporary feedback that the request has been sent */
	f.ajaxInProgress=true;
	var ph=f.progressHandler;
	if(ph)ph.call(this,f);
	return false;
}

// To have a form use AJAX, during window.onload:
//	ajaxFormSetup('my-form-id','submit',ajaxFormSubmit)
//
// form - the form to submit via ajax (required)
// responseHandler - the function to invoke upon response. (optional)
//	the handler will get two args: the server response and the form element.
// progressHandler - the function to invoke upon request submission (optional)
//	the handler will get one arg: the form element.
//	the form will have a parameter 'ajaxInProgress' as true if ajax in progress.
function ajaxFormSetup(form,responseHandler,progressHandler){
	form=xGetElementById(form);
	if(responseHandler)form['responseHandler']=responseHandler;
	if(progressHandler)form['progressHandler']=progressHandler;
	xAddEventListener(form,'submit',ajaxFormSubmit,false);
}

// Reads the response from the specific url and returns it as a string synchronously.
// Response must be valid XML
//
// url - the url to read from
function getRequest(url){
	var doc = Sarissa.getDomDocument();
	doc.async = false;
	doc.load(url);
	if(doc.parseError!=0){
		alert(Sarissa.getParseErrorText(doc));
	}else{
		return Sarissa.serialize(doc);
	}
}
