/////////////////////////////////////////////////////////////// JS
// js_ajax.js - Simple AJAX - Filippo Grassilli
/////////////////////////////////////////////////////////////// JS

function simpleAjax() {
    // Properties
    var xmlReq=null;
    var saDiv=null;
    var saDivId="simpleAjaxDiv";
    var customHandler=null

    // Methods
    this.postForm=postForm;
    this.sendReq=sendReq;
    this.setTarget=setTarget;
    this.setHandler=setHandler;

    // Public
    function sendReq(url) {
	if(xmlReq) return;
	if(!saDiv) saDiv=document.getElementById(saDivId);
	createXMLReq();
	xmlReq.open("GET",url,true);
	xmlReq.send(null);
    }
    function postForm(frm) {
	var params;
	if(xmlReq) return;
	if(!saDiv) saDiv=document.getElementById(saDivId);
	createXMLReq();
	params=form2QS(frm);
	// alert(params);
	xmlReq.open("POST",frm.action,true);
	xmlReq.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
	xmlReq.setRequestHeader("Content-Length",params.length);
	xmlReq.setRequestHeader("Connection","close");
	xmlReq.send(params);
    }
    function setTarget(tid) {
	saDivId=tid;
	saDiv=null;
    }
    function setHandler(fn) {
	customHandler=fn;
    }
    // Private
    function createXMLReq() {
	var xmlhttp=null;
	try {
	    xmlhttp=new XMLHttpRequest();
	} catch(e) {
	    try {
		xmlhttp=new ActiveXObject("Msxml2.XMLHTTP");
	    } catch(e) {
		xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
	    }
	}
	try { xmlhttp.overrideMimeType("text/html"); } catch(e) {}
	xmlhttp.onreadystatechange=stdHandler;
	xmlReq=xmlhttp;
	return(xmlhttp);
    }
    function stdHandler() {
	if(xmlReq.readyState==4) {
	    if(saDiv) saDiv.innerHTML=xmlReq.responseText;
	    try {
	    customHandler(xmlReq.responseText);
	    } catch(e) {}
	    xmlReq=null;
	}
    }
    function form2QS(frm) {
	var qstr="";
	var frmEl;
	function addElement(name,val) {
	    qstr+=(qstr.length>0?'&':'')+encodeURIComponent(name)+'='+encodeURIComponent(val?val:'');
	}
	for(var f=0; f<frm.elements.length; f++) {
	    frmEl=frm.elements[f];
	    switch(frmEl.type) {
		case 'text':
		case 'select-one':
		case 'hidden':
		case 'password':
		case 'textarea':
		    addElement(frmEl.name,frmEl.value);
		    break;
		case 'checkbox':
		case 'radio':
		    if(frmEl.checked==true)
			addElement(frmEl.name,frmEl.value);
		    break;
		default:
		    // alert(f+') '+frmEl.type+' '+frmEl.name+'='+frmEl.value+' checked='+frmEl.checked);
		    break;
	    }
	}
	// alert(qstr);
	return(qstr);
    }
}
