var xhr = new Array(); // ARRAY OF XML-HTTP REQUESTS
var xi = new Array(0); // ARRAY OF XML-HTTP REQUEST INDEXES
xi[0] = 1; // FIRST INDEX SET TO 1 MAKING IT AVAILABLE
function xhrRequest(type){
	
	if (!type) {
		type = 'html';
	}

	// xhrsend IS THE xi POSITION THAT GETS PASSED BACK
	// INITIALIZED TO THE LENGTH OF THE ARRAY(LAST POSITION + 1)
	// IN CASE A FREE RESOURCE ISN'T FOUND IN THE LOOP
	var xhrsend = xi.length; 
	
	// GO THROUGH AVAILABLE xi VALUES
	for (var i=0; i<xi.length; i++) {

		// IF IT'S 1 (AVAILABLE), ALLOCATE IT FOR USE AND BREAK
		if (xi[i] == 1) {
			xi[i] = 0;
			xhrsend = i;
			break;
		}
	}

	// SET TO 0 SINCE IT'S NOW ALLOCATED FOR USE
	xi[xhrsend] = 0;

	// SET UP THE REQUEST
	if (window.ActiveXObject) {
		try {
			xhr[xhrsend] = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e) {
			try {
				xhr[xhrsend] = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (e) {}
		}
	} else if (window.XMLHttpRequest) {
		xhr[xhrsend] = new XMLHttpRequest();
		if (xhr[xhrsend].overrideMimeType) {
			xhr[xhrsend].overrideMimeType('text/' + type);
		}
	}
	return (xhrsend);
}

function genera_calendario(mes, anio){
		var divResultado = document.getElementById('divimgcalen');
		var xhri = xhrRequest('html');
		var url = 'calendarip.php?mes=' + mes + '&anio=' + anio + '&RANDOM=' + (Math.random() * Date.parse(new Date())) 
		xhr[xhri].open("GET", url);
		xhr[xhri].onreadystatechange=function() {
				if (xhr[xhri].readyState!=4) {
				divResultado.innerHTML='<span class="spanstatus">Cargando</span><br><img src ="img/load.gif" align="absmiddle">';
		}
			if (xhr[xhri].readyState==4) {
		
				if(xhr[xhri].responseText !=''){
				divResultado.innerHTML = xhr[xhri].responseText
				var aniomenos = anio - 1;
				var aniomas =  anio + 1;
				var mesmenos =  mes - 1;
				var mesmas =  mes + 1;
				aniodemes=anio;
				anioizmes=anio;
				if (mes==12){
						mesmas=1;
						aniodemes=anio + 1;
					}
				if (mes==1){
						mesmenos=12;
						anioizmes=anio -1;
					}
				
					document.getElementById('izan').onclick=function(){
						genera_calendario( mes , aniomenos );
						return false;
					}
					document.getElementById('izmes').onclick=function(){
						genera_calendario( mesmenos , anioizmes );
						return false;
					}
					document.getElementById('demes').onclick=function(){
						genera_calendario(mesmas, aniodemes);
						return false;
					}
					
					document.getElementById('dean').onclick=function(){
						genera_calendario(mes,aniomas);
						return false;
					}
				}
			}
		}
		xhr[xhri].send(null)
}
