// ---------------------------------------------------
// -  A set of functions handling AJAX requests  -
// ---------------------------------------------------

//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] = 'news_story'+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;
			if (httpHost=='localhost') {
				url = 'http://localhost/dotdotdotcomma.com/ajax/news.php?id='+action;
			} else {
				//Handle http://www.dotdotdotcomma.com and http://dotdotdotcomma.com
				url = 'http://'+httpHost+'/ajax/news.php?id='+action;
			}
			httpRequest.open('GET',url,true);
			httpRequest.send(null);
		} 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 news item's ID from the name of the enclosing <div>
			idNo = currentContainer.replace(/news_story/gi, "");
			//Grab a reference to the item's div
			var divObj = document.getElementById(currentContainer);
//			//Populate the <div> with the text of the news item and a link that allows the user to e-mail the article
//			divObj.innerHTML = httpRequest.responseText+"<div class='body_dark' style='width:100%;text-align:center;'><a class='bodylink' href='email_article.php?id="+idNo+"'>send this article to a friend</a></div>";
			//Populate the <div> with the text of the news item
			divObj.innerHTML = httpRequest.responseText;
			requestIndex++;
			submitRequest(requestIndex);
		} else {
			//There was a problem with the request
		}
	}
}

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

//Show or hide all news items
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?
		var showItems = (linkObj.innerHTML.toLowerCase()=="<b>show&nbsp;all</b>");
		//Run through the array of news item IDs and display or hide each one in turn
		for (var newsIDRow=0;newsIDRow<newsIDs.length;newsIDRow++) {
			displayStory(newsIDs[newsIDRow],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 news item
function displayStory(idNo,displayItem) {
	//Grab a reference to the news item's <div>
	objRef = document.getElementById("news_story"+idNo);
	if (displayItem) {
		//Has the news item previously been requested via AJAX?
		if (objRef.innerHTML=='') {
			//No, so display a "Loading...," message and request the news item
			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 news item. As an alternative, you can select news items (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 story
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 news story
function getReqAction(reqIndex) {
	if (reqIndex<queueRequests.length) {
		return queueRequests[reqIndex];
	}
}

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

//Return the ID of a requested news story'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 news item's text <div>
var currentContainer = null;
//A reference to the current news item'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;

