var numListings = 2;

function buildList(listingsString) {
	
		// add the listings
	var listings = listingsString.split("||||");
	for (i=0; i<listings.length; i++) {
		var timeProg = listings[i].split("^^^^");
		if (listings[i] != "" && timeProg.length == 2 && i < numListings) { 
			var newListing = document.createElement("li");
			newListing.id = "listing" + i;
			newListing.className = "tvListings";
			newListing.innerHTML = "<strong>" + timeProg[0] + "" + "</strong><span>" + timeProg[1] + "</span>";
			document.getElementById("listingsList").appendChild(newListing);
		}
	}
}

var http_request_nowshowing = false;

function makePOSTRequestNowShow(url, parameters) {

	http_request_nowshowing = false;
	if (window.XMLHttpRequest) {									// dom complient browsers and IE7
		http_request_nowshowing = new XMLHttpRequest();
		if (http_request_nowshowing.overrideMimeType) {
			http_request_nowshowing.overrideMimeType('text/html');				// assume not valid xml
		}
	} else if (window.ActiveXObject) {								// IE5/5.5/6 - uses ActiveX approximation
		try {
			http_request_nowshowing = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e) {
			try {
				http_request_nowshowing = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (e) {}
		}
	}

	http_request_nowshowing.onreadystatechange = processRequestNowShow;
	http_request_nowshowing.open('POST', url, true);
	http_request_nowshowing.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	http_request_nowshowing.setRequestHeader("Content-length", parameters.length);
	http_request_nowshowing.setRequestHeader("Connection", "close");
	http_request_nowshowing.send(parameters);
	
}

function processRequestNowShow() {

	if (http_request_nowshowing.readyState == 4) {
		if (http_request_nowshowing.status == 200) {
		
				// response ok
		
			buildList(http_request_nowshowing.responseText);
		} else {
		
				// response fails display error message...
		
			var newListing = document.createElement("li");
			newListing.id = "nolisting";
			newListing.className = "tvListings";
			newListing.innerHTML = "Sorry, no listings information is available at this time.";
			document.getElementById("listingsList").appendChild(newListing);
		}
	}
}

function sendListingsRequest(channel_code, language_code, num_programs, min_offset) {
	
		// send xhttp request

	var requestString = "";
		requestString += "channel_code=" + channel_code;
		requestString += "&language_code=" + language_code;
		requestString += "&next_programme_number=" + num_programs;
		if(min_offset){
			requestString += "&minute_offset=" + min_offset;
		}
	makePOSTRequestNowShow('/tvlistings/nowShowingAjax.jsp', requestString);
}

