// ------------------------------------------------------------------------
// -  A set of functions handling AJAX requests for the F1 Records pages  -
// ------------------------------------------------------------------------

//Master function that attempts to create an XML HTTP request object, depending
//on the browser being used. If the object cannot be created, FALSE is returned.
function createRequestObject() {
	var reqObj = false;
	if (window.XMLHttpRequest) {
		//Non-MS browser
		reqObj = new XMLHttpRequest();
	} else if (window.ActiveXObject) {
		//Use MS ActiveX
		try {
			//Try object supported by later versions of IE
			reqObj = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (error1) {
			try {
				//Try object supported by older versions of IE
				reqObj = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (error2) {
				//Browser doesn't support XML HTTP requests
			}
		}
	}
	return reqObj;
}

//Add a request to the AJAX queue
function addRequest(idNo) {
	if (!inArray(idNo,queueRequests)) {
		queueRequests[arrayIndex] = idNo;
		queueTargets[arrayIndex] = 'record'+idNo;
		queueImages[arrayIndex] = 'item_image'+idNo;
		arrayIndex++;
	}
}

//Kick off the process of working through the AJAX queue
function requestStart() {
	if (queueRequests.length==0) {
		//No requests scheduled
		return;
	} else {
		if (requestIndex<=queueRequests.length-1) {
			submitRequest(requestIndex);
		}
	}
}

//Submit a request from the AJAX queue
function submitRequest(reqIndex) {
	if (reqIndex!=null) {
		if (reqIndex<=queueRequests.length-1) {
			action = getReqAction(reqIndex);
			target = getReqTarget(reqIndex);
			image = getReqImage(reqIndex);
			httpRequest = createRequestObject();
			httpRequest.onreadystatechange = processRequest;
			currentContainer = target;
			currentImage = image;
			//GET
//			url = 'http://www.dotdotdotcomma.com/ajax/records.php?id='+action;
//			//url = 'http://dotdotdotcomma.com/ajax/records.php?id='+action;
//			httpRequest.open('GET', url, true);
//			httpRequest.send(null);
			//POST
			httpRequest.onreadystatechange = processRequest;
			if (httpHost=='localhost') {
				url = 'http://localhost/dotdotdotcomma.com/ajax/f1records.php';
			} else {
				//Handle http://www.dotdotdotcomma.com and http://dotdotdotcomma.com
				url = 'http://'+httpHost+'/ajax/f1records.php';
			}
			params = 'id='+action;
			httpRequest.open('POST', url, true);
			//Send the proper header information with the request
			httpRequest.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
			httpRequest.send(params);
		} else {
			if (reqIndex>queueRequests.length-1) {
				//Invalid request index: no more requests exist
			}
			return;
		}
	}
}

//This is the function that actually does something with the returned request
function processRequest() {
	if (httpRequest.readyState==4) {
		if (httpRequest.status==200) {
			//Extract the record's ID from the name of the enclosing <div>
			idNo = currentContainer.replace(/record/gi, "");
			//Grab a reference to the item's div
			var divObj = document.getElementById(currentContainer);
			//Populate the <div> with the text of the record item
			divObj.innerHTML = unescape(httpRequest.responseText).replace(/\+/g, ' ');
			requestIndex++;
			submitRequest(requestIndex);
		} else {
			//There was a problem with the request
		}
	}
}

//Show or hide a specified record
function toggleRecord(idNo, httpHostName) {
	//Record the HTTP host name
	httpHost = httpHostName;
	//Grab a reference to the record's <div>
	objRef = document.getElementById("record"+idNo);
	//Add the record to the request queue
	displayRecord(idNo,objRef.style.display=='none');
	//Kick off the AJAX requests
	requestStart();
}

//Show or hide all records
function toggleAll(itemCount) {
	if (itemCount>20) {
		alert("The number of items in the current list exceeds the number\nthat can be expanded at once.\n\nPlease change your selected filter or view items individually.");
	} else {
		//Grab a reference to the "SHOW ALL"/"HIDE ALL" link
		linkObj = document.getElementById("togglealllink");
		//Are we showing or hiding?
		showItems = (linkObj.innerHTML.toLowerCase()=="<b>show&nbsp;all</b>");
		//Run through the array of record IDs and display or hide each one in turn
		for (var recordIDRow=0;recordIDRow<recordIDs.length;recordIDRow++) {
			displayRecord(recordIDs[recordIDRow],showItems);
		}
		//Kick off the AJAX requests
		requestStart();
		//Update the link text
		linkObj.innerHTML = (showItems ? "<b>hide&nbsp;all</b>" : "<b>show&nbsp;all</b>");
	}
}

//Display a single record
function displayRecord(idNo,displayItem) {
	//Grab a reference to the record's <div>
	objRef = document.getElementById("record"+idNo);
	if (displayItem) {
		//Has the record previously been requested via AJAX?
		if (objRef.innerHTML=='') {
			//No, so display a "Loading...," message and request the record
			objRef.innerHTML = loadingMessage;
			//Show the div
			toggleDiv(objRef,document.getElementById("item_image"+idNo),true);
			addRequest(idNo);
		} else {
			//Yes, so just display the thing
			toggleDiv(objRef,document.getElementById("item_image"+idNo),true);
		}
	} else {
		//Grab a reference to the item's image
		imgObj = document.getElementById('item_image'+idNo);
		//Hide the div
		toggleDiv(objRef,imgObj,false);
	}

	//If the httpRequest variable is false, we can go no further, so display a message to that effect.
	if (!httpRequest) {
		objRef.innerHTML = "<div class='body_light_blacktext'><b>Your browser does not appear to support AJAX, which this page is trying to use to display the record. As an alternative, you can select records (using the checkboxes on the right) and then click the &quot;View item(s)&quot; button to see the selected stories.</b></div>";
	}


}

//Toggle the elements that make up a record
function toggleDiv(objRef,imgObj,display) {
	//Show or hide the div
	objRef.style.display = (display ? '' : 'none');
	//Add or remove the border
	objRef.style.border = (display ? '2px solid #75736E' : '');
	//Switch the "collapse/expand" image
	imgObj.src = (display ? '../../../images/item_collapse.jpg' : '../../../images/item_expand.jpg');
}

//Return the ID of a requested record
function getReqAction(reqIndex) {
	if (reqIndex<queueRequests.length) {
		return queueRequests[reqIndex];
	}
}

//Return the ID of a requested record <div>
function getReqTarget(reqIndex) {
	if (reqIndex<queueTargets.length) {
		return queueTargets[reqIndex];
	}
}

//Return the ID of a requested record's expand/collapse image
function getReqImage(reqIndex) {
	if (reqIndex<queueImages.length) {
		return queueImages[reqIndex];
	}
}


//Define the HTML that will be displayed while we are waiting for the AJAX
//request to be returned
var loadingMessage = "<div class='body_light_blacktext'><b>Loading...,</b></div>";

//Initialise the HTTP multiple request object to false
//var httpRequest = false;
var httpRequest = createRequestObject();
//A reference to the current record's text <div>
var currentContainer = null;
//A reference to the current record's image <div>
var currentImage = null;

//Three parallel arrays, to hold request information and respective target and image IDs
var queueRequests = new Array();
var queueTargets = new Array();
var queueImages = new Array();
//The current index of the queueRequests, queueTargets and queueImages arrays
var arrayIndex = 0;
//The current request
var requestIndex = 0;

//The current page's HTTP host name (e.g. "localhost" or "www.dotdotdotcomma.com")
var httpHost;

