ajaxob = function(){
	return (window.XMLHttpRequest) ?
	new XMLHttpRequest() :
	new ActiveXobject('Microsoft.XMLHTTP') 
}
ajupload = function(i){
	var ifm = make_a('iframe');
	with(ifm){
		setAttribute('id','uploadframe');
		setAttribute('src','savedata.php');
	}
}
callserver = function(url, box, f){
	give(box,'');
	var ob = ajaxob();
	ob.onreadystatechange = function(){
		if(ob.readyState < 4) box.innerHTML = "loading...";
		if(ob.readyState == 4){
			if(ob.status == 200){
				if(box) box.innerHTML = ob.responseText;
				if(f) f()
			} else 
				alert('ajax problem')
		}
	}
	ob.open("GET", url, true);
	ob.send(null) 
}
collect_form = function(frm, sep){
	var sep = sep || '&';
	var flds = toArray(frm.childNodes);
	var reqflds = flds.filter(function(x){return x.nodeName == 'INPUT'});
	var reqflds = reqflds.filter(function(x){return x.name != 'submit'});
	var reqflds = reqflds.map(function(x){return x.name+'='+x.value+sep});
	return reqflds 
}
wl = function(f){
	var old = window.onload;
	if(typeof(old)!='function') window.onload = f;
	else window.onload = function(){
		old();
		f(); 
	} 
}
addEvt = function(ob, trg, f){
	(ob.addEventListener) ?
		ob.addEventListener(evt, act, false) :
		ob.attachEvent('on'+evt, act); }

$ = function(x){ return document.getElementById(x); }

toArray = function(x){
	var newArray = [];
	for(var i=0; i<x.length; i++){
		newArray.push(x[i]); }
	return newArray; }

$T = function(x){
	var lst = document.getElementsByTagName(x);
	if(!lst) return;
	else return toArray(lst);	}

give = function(ctnr, stf){ ctnr.innerHTML = stf; }

genloop = function(g,f,origlst){
	if(!origlst) return false;
	var newlst = [];

	inloop = function(g,f,origlst){
		if(origlst.length < 1) return newlst;
		g(f,origlst,newlst);
		return inloop(g,f,origlst.tail()); }

	return inloop(g,f,origlst); }

Array.prototype.head = function(){
    if(!this.length) return false;
    return this[0] 
}

Array.prototype.tail = function(){
    if(this.length < 1) return;
    return (this.slice(1))
}

Array.prototype.map = function(f){
	return genloop(function(f,orig,n){
		n.push(f(orig.head())); },
	f,
	this ) 
}

Array.prototype.filter = function(f){
	return genloop(
		function(f,orig,n){
			if(f(orig.head())) n.push(orig.head()); 
		},
		f,
		this
	) 
}

Array.prototype.reduce = function( acc ){
	var acc = acc || '';
	this.map( function(x){ acc += x });
	return acc 
}

String.prototype.humanize = function(){
	var cap = this.charAt(0).toUpperCase();
	var rest = this.substring(1).replace(/_/, ' ');
	return cap + rest
}

make_a = function(x){return document.createElement(x)}

toggle = function(x){
	return function(){
		x.reset();
		x.style.display = (x.style.display == 'none') ? '' : 'none'; 
	} 
}

reveal = function(x,lst){
	return function(){
		lst.map(function(x){ $(x).style.display='none'} );
		$(x).style.display='' 
	} 
}

doclientlinks = function(){
	lks.map(function(x){
		$(x).onclick = function(){
		var t=$(x).getAttribute('table');
		var i=$(x).getAttribute('idf');
		callserver(
			'/js/fetchlist.php?table='+t+'&id='+i,
			$('info'),
			function(){
				map_eds_dels();
				$('new_'+t).onclick=function(){
					var flds=lookupfields(t)
				}
			}
		)}
	})
}

lookupfields = function(table){
	var tempdiv = make_a('div');
	callserver(
		'/js/lookupfields.php?tablename='+table,
		tempdiv,
		function(){
			var set = eval('(' + tempdiv.innerHTML + ')');
			var newform = makeform({name:table, id:table, data:set});
			$('info').innerHTML = newform;
			var client_id = $('list').firstChild.firstChild.innerHTML;
			document.forms['form'+table].client_id.value = client_id
			document.forms['form'+table].onsubmit = function(){
				saveform(this, table); return false
			}
		 } 
	) 
}

makeform = function(ob){
	var formname = ob.name || '';
	var formid = ob.id || '';
	var formcls = ob.class || '';
	var s = "<form name='form"+formname+"' id='form"+formid+"' class='"+formcls+"' enctype='multipart/form-data' method='POST'>";

	for(var fld in ob.data){
		if(ob.data[fld] != 'hidden') 
			s += "<label for='"+fld+"'>" + fld.humanize() + "</label>";
		s += "<input name='"+fld+"' type='" + ob.data[fld] + "'>"
	}
	s += "<input type='submit' name='submit' value='Guardar'></form>";
	return s
}

delrecord = function(record){
	var confirm = window.confirm('Estas seguro?');
	if(!confirm)return false;
	var table = record.getAttribute('table');
	var id = record.getAttribute('idr');
	var tempdiv = make_a('div');
	callserver(
		'/js/remove.php?id='+id+'&table='+table,
		tempdiv,
		function(){record.parentNode.style.display='none'}
	)
}

map_eds_dels = function(){
	var as = toArray(document.getElementsByTagName('a'));
	var es = as.filter(function(x){return /edit/.test(x.className)})
	var ds = as.filter(function(x){return /del/.test(x.className)})

	es.map(function(x){
		x.onclick=function(){
			fillform(this.getAttribute('table'), this.getAttribute('idr'))
		}
	})

	ds.map(function(x){
		x.onclick=function(){ alert(this); delrecord(this) }
	})
}

fillform = function(table,id){
	callserver(
		'/js/fetchrecord.php?table='+table+'&id='+id,
		$('info'),
		function(){
			document.forms['form'+table].onsubmit = function(){ saveform(this, table); return false }
			var as = toArray(document.getElementsByTagName('a'));
			var eds = as.filter(function(x){ return /edit/.test(x.className) })
		}
	)
}

saveform = function(frm, table){
	var frmdata = collect_form(frm);
	var frmstr  = frmdata.reduce('');
	var frmstr = frmstr + '&table='+table;
	callserver(
		'/js/saveform.php?'+frmstr,
		$('msg'),
		function(){}
	)
}

var addrs = ['nc','ap','ac','as','ad'];
var lks = ['ps','ss1','ss2','ds'];
var dvs = lks.map(function(x){return x+'div'});

wl(function(){
	$('nc').onclick=function(){
		var dis = $('clientform').style.display;
		$('clientform').style.display = (dis == 'none') ? '' : 'none';
	}
	$('getclients').onclick = function(){
		var nombre = document.searchform.nombre.value;
		var ref = document.searchform.ref.value;
		callserver(
			'/js/fetchclients.php?id='+ref+'&nombre='+nombre,
			$('list'),
			function(){ doclientlinks()}
		)
	}
})
