// Determines whether e is contained in array a
function contains(a, e) {
	for(j=0;j<a.length;j++)if(a[j]==e)return true;
	return false;
}

function escapeHTML (str) {
   var div = document.createElement('div');
   var text = document.createTextNode(str);
   div.appendChild(text);
   return div.innerHTML;
}; 

/* The following function creates an XMLHttpRequest object... */

function createRequestObject(){
	var request_o; //declare the variable to hold the object.
	var browser = navigator.appName; //find the browser name
	
	if(browser == "Microsoft Internet Explorer"){
		/* Create the object using MSIE's method */
		request_o = new ActiveXObject("Microsoft.XMLHTTP");
	}else{
		/* Create the object using other browser's method */
		request_o = new XMLHttpRequest();
	}

	return request_o; //return the object
}

/* You can get more specific with version information by using 
	parseInt(navigator.appVersion)
	Which will extract an integer value containing the version 
	of the browser being used.
*/
/* The variable http will hold our new XMLHttpRequest object. */
var http = createRequestObject(); 
// This contains the text representing which input the event was fired from
var from_source = "";
// Set the default limit
var limit = 10;
// Set the current page
var page_number = 1;
// Set the maximum pages
var max_pages = 0;

/* Function called to get the product categories list */
function getCars(source){
	/* Create the request. The first argument to the open function is the method (POST/GET),
		and the second argument is the url... 
		document contains references to all items on the page
		We can reference document.form_category_select.select_category_select and we will 		
		be referencing the dropdown list. The selectedIndex property will give us the 
		index of the selected item. 
	*/
	//http.open('get', 'internal_request.php?action=get_products&id=' 
	//		+ document.form_category_select.select_category_select.selectedIndex);
	// Determine the combo box that was selected
	from_source = source;
	
	page_number = document.getElementById("current_page").value;

	// Determine whether to reset the values of range and model
	if((from_source == "range") && (document.car_search.range.value == 0)){
		document.car_search.model.value = 0;
	}
	
	if(from_source == "search"){
		page_number = 1;
		document.getElementById("current_page").value = 1;
	}
	
	ordering_value = document.getElementById("search_ordering").value;
	limit_value = document.getElementById("car_limit_select").value;

	if(limit_value == 0){
		limit = 10;
	}
	else if(limit_value == 1){
		limit = 15;
	}
	else if (limit_value == 2){
		limit = 20;
	}
	else if (limit_value == 3){
		limit = 25;
	}
	
	max_pages = document.getElementById('current_page').value;

	//http.abort;
	http.open('post',  'form_processing/internal_request.php');
	http.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
	http.send('range='+ document.car_search.range.value + '&model='+ document.car_search.model.value + '&transmission='+ document.car_search.transmission.value + '&fuel_type=' + document.car_search.fuel.value + '&ordering=' + ordering_value + '&limit=' + limit_value + '&page=' + page_number + '&source=' + from_source + '&limit_total=' + limit + '&max_pages_old=' + max_pages);
	/* Define a function to call once a response has been received. This will be our
		handleProductCategories function that we define below. */
	http.onreadystatechange = handleProducts; 
	/* Send the data. We use something other than null when we are sending using the POST
		method. */
	//http.send(null);
}

// This function returns the array of items based on what is read from the xml
function returnItemArray(item_list){
	// Initialise the array
	itemArray = [];

	// For the number of cars in the list
	for(i=0; i<item_list.length; i++){ //length is the same as count($array)
		// Determine the values associated with the car
		id = item_list[i].getAttribute('id') //Grabs the id attribute.
		
		// Determine the range details
		range = item_list[i].getElementsByTagName("range")[0];
		if(range.hasChildNodes()){
			range_text = range.childNodes[0].nodeValue;
		}
		else {
			range_text = "";
		}
		range_id = range.getAttribute('id');
		// Determine the model details
		model = item_list[i].getElementsByTagName("model")[0];
		if(model.hasChildNodes()){
			model_text = model.childNodes[0].nodeValue;
		}
		else {
			model_text = "";
		}
		model_id = model.getAttribute('id');
		// Determine the derivative
		derivative = item_list[i].getElementsByTagName("derivative")[0];
		if(derivative.hasChildNodes()){
			derivative_text = derivative.childNodes[0].nodeValue;
		}
		else {
			derivative_text = "";
		}
		// Determine the transmission details
		transmission = item_list[i].getElementsByTagName("transmission")[0];
		if(transmission.hasChildNodes()){
			transmission_text = transmission.childNodes[0].nodeValue;
		}
		else {
			transmission_text = "";
		}
		// Determine the fuel details
		fuel = item_list[i].getElementsByTagName("fuel")[0];
		if(fuel.hasChildNodes()){
			fuel_text = fuel.childNodes[0].nodeValue;
		}
		else {
			fuel_text = "";
		}
		// Determine the fuel delivery details
		fuel_delivery = item_list[i].getElementsByTagName("fuel_delivery")[0];
		if(fuel_delivery.hasChildNodes()){
			fuel_delivery_text = fuel_delivery.childNodes[0].nodeValue;
		}
		else {
			fuel_delivery_text = "";
		}
		// Determine the trim details
		trim_node = item_list[i].getElementsByTagName("trim")[0];
		if(trim_node.hasChildNodes()){
			trim_text = trim_node.childNodes[0].nodeValue;
		}
		else {
			trim_text = "";
		}
		// Determine the drivetrain details
		drivetrain = item_list[i].getElementsByTagName("drivetrain")[0];
		if(drivetrain.hasChildNodes()){
			drivetrain_text = drivetrain.childNodes[0].nodeValue;
		}
		else {
			drivetrain_text = "";
		}
		// Determine the body details
		body_node = item_list[i].getElementsByTagName("bodystyle")[0];
		if(body_node.hasChildNodes()){
			body_text = body_node.childNodes[0].nodeValue;
		}
		else {
			body_text = "";
		}
		// Determine the door details
		doors = item_list[i].getElementsByTagName("doors")[0];
		if(doors.hasChildNodes()){
			doors_text = doors.childNodes[0].nodeValue;
		}
		else {
			doors_text = "";
		}
		// Determine the price details
		price = item_list[i].getElementsByTagName("price")[0];
		if(price.hasChildNodes()){
			price_text = price.childNodes[0].nodeValue;
		}
		else {
			price_text = "";
		}
		
		// Determine the image details
		image = item_list[i].getElementsByTagName("image")[0];
		if(image.hasChildNodes()){
			image_text = image.childNodes[0].nodeValue;
		}
		else {
			image_text = "";
		}
		
		// Add there values to an element representing the car
		var currentCar = [id, range_text, range_id, model_text, model_id, derivative_text, transmission_text, fuel_text, fuel_delivery_text, trim_text, drivetrain_text, body_text, doors_text, price_text, image_text];
		// Push this element into the car array
		itemArray.push(currentCar);
	}
	
	return itemArray;
}

// This function updates the select box details for an individual select
function updateSelect( select_box, xmlresponse ){
	
	// Get the names to search for
	select_box_name = select_box + "_select";
	
	// Get the list for the select
	select_list = xmlresponse.getElementsByTagName(select_box_name);
	
	// Get the select from the document
	select_combo = document.getElementById(select_box_name);
	// Get the selected div
	selected_div = document.getElementById(select_box_name+"_div");
	// Get the current value
	selected_value = select_combo.value;

	// Initialise the new select html
	select_html = '<select id="' + select_box_name + '" name="' + select_box + '" onchange="getCars(\'' + select_box + '\');" ><option value="0">Any</option>';

	// For the number of items in the select
	for(i=0; i<select_list.length; i++){ 
		current_id = select_list[i].getAttribute('id');
	
		if(select_list[i].hasChildNodes()){
			current_text = select_list[i].childNodes[0].nodeValue;
		}
		else {
			current_text = "";
		}

		if(current_id == selected_value){
			selected = " selected ";
		}
		else {
			selected = "";
		}
		select_html = select_html + '<option value="'+current_id+'"'+selected+'>'+current_text+'</option>'
	}
	select_html = select_html + '</select>';
	select_combo.disabled = false;

	// Update the html
	selected_div.innerHTML = select_html;
	
	// Select the combo again
	select_combo2 = document.getElementById(select_box_name);
	
	if((select_box == "model") && (document.getElementById("range_select").value == 0)){
		select_combo2.disabled = true;
	}
}

// This function will update the html contents to display the pager
function outputPager(page_number, max_pages){
	// Initialise the page array
	var page_array = [];
	
	// Set the page number to be an int
	var page_number_int = parseInt(page_number);
	
	// Initialise the position of the dots
	var dot1 = 0;
	var dot2 = 0;
	
	// Calculate the threshholds at the lower and upper bounds
	if((page_number_int == 1) || (page_number_int == 2)){
		threshhold = 3;
	}
	else {
		threshhold = 2;
	}
	if((page_number_int == max_pages) || (page_number_int == (max_pages - 1))){
		threshhold2 = max_pages - 2;
	}
	else {
		threshhold2 = max_pages - 1;
	}
	
	// For all the possible pages
	for(var i = 1 ; i <= max_pages ; i++){
		// If the page number should be displayed then add it to the array
		if((i <= threshhold) || (i >= (threshhold2)) || ((i <= (page_number_int+1)) && (i >= (page_number_int-1)))){
			page_array.push(i);
		}
	}
	
	if((max_pages > 5) && (max_pages < 9)){
		test_limit = (max_pages - 5);
		if((page_number_int == 1) || (page_number_int == 2)){
			dot1 = 3;
		}
		else if(page_number_int <= (1 + test_limit)){
			dot1 = page_number_int + 1;
		}
		else if(page_number >= (max_pages - test_limit)){
			dot1 = 2;
		}
	}
	else if(max_pages >= 9){
		if((page_number_int == 1) || (page_number_int == 2)){
			dot1 = 3;
		}
		else if(page_number >= (max_pages - 3)){
			dot1 = 2;
		}
		else if(page_number_int <= 4){
			dot1 = page_number_int + 1;
		}
		else {
			dot1 = 2;
			dot2 = 5;
		}
	}
	
	pagerHTML = "";
	
	if(page_number_int != 1){
		pagerHTML = pagerHTML + "<a href=\"page/cars_new_search/#\" title=\"Previous Page\" onclick=\"document.getElementById('current_page').value="+(page_number_int-1)+";getCars('pager');return false;\">&lt;</a>\n";
	}
	
	for(var i = 0 ; i < page_array.length ; i++){
		if(page_array[i] == page_number_int){
			underlined = "style=\"text-decoration:underline;\"";
		}
		else {
			underlined = "";
		}
		
		pagerHTML = pagerHTML + "<a href=\"page/cars_new_search/#\" title=\"Page "+page_array[i]+"\" "+underlined+" onclick=\"document.getElementById('current_page').value="+page_array[i]+";getCars('pager');return false;\">"+page_array[i]+"</a>\n"	
	
		if((i+1) == dot1){
			pagerHTML = pagerHTML + "...\n";
		}
		else if((i+1) == dot2){
			pagerHTML = pagerHTML + "...\n";
		}
	}
	
	if(page_number_int != max_pages){
		pagerHTML = pagerHTML + "<a href=\"page/cars_new_search/#\" title=\"Next Page\" onclick=\"document.getElementById('current_page').value="+(page_number_int+1)+";getCars('pager');return false;\">&gt;</a>\n";
	}
	
	document.getElementById('pager_container').innerHTML = pagerHTML;
	document.getElementById('pager_container2').innerHTML = pagerHTML;
}

/* Function called to handle the list that was returned from the internal_request.php file.. */
function handleProducts(){
	/* Make sure that the transaction has finished. The XMLHttpRequest object 
		has a property called readyState with several states:
		0: Uninitialized
		1: Loading
		2: Loaded
		3: Interactive
		4: Finished */
	if(http.readyState == 4){ //Finished loading the response
		/* We have got the response from the server-side script,
			let's see just what it was. using the responseText property of 
			the XMLHttpRequest object. */
		var response = http.responseXML;
		/* Reference the product_list element to the variable product_list */
		
		car_list_array = response.getElementsByTagName("car");
		
		car_new_total = response.getElementsByTagName("new_car_total")[0].getAttribute('id');

		// Initialise the array to be empty
		var carArray = returnItemArray(car_list_array);
		
		// If the max_pages has been set store their value
		max_pages_old = max_pages;
	
		// Get the maximum pages
		max_pages = Math.ceil(carArray.length / limit);
	
		if(max_pages_old != 0){
			if(from_source == "limit"){
				if(max_pages < max_pages_old){
					ratio = max_pages / max_pages_old;
					page_number = Math.ceil(ratio * page_number);
					document.getElementById("current_page").value = page_number;
				}
			}
		}
			
		// Build the text that will be displayed on the page
		var responsetext = ""
		
		// Calculate the start item
		start = (page_number - 1) * limit
		
		// Calculate the end item
		if(carArray.length < (start + limit)){
			end = carArray.length
		}
		else {
			end = start + limit;
		}

		// For the number of cars in the list
		for(i=start; i<end; i++){ //length is the same as count($array)
			// Get the required details
			id = carArray[i][0];
			range = carArray[i][1];
			range_code = carArray[i][2];
			model = carArray[i][3];
			derivative = carArray[i][5];
			trim = carArray[i][9];
			drivetrain = carArray[i][10];
			fuel_type = carArray[i][7];
			fuel_delivery = carArray[i][8];
			transmission = carArray[i][6];
			body = carArray[i][11];
			doors = carArray[i][12];
			price = carArray[i][13];
			image	= carArray[i][14];
			// Append the current item to the text string	
			//responsetext = responsetext + "<p>Range: " + range + "<br/>Model: " + model + "<br/>Derivative: " + derivative + "</p>";
			responsetext = responsetext 
			+"<div class=\"searchresult\">"
				+"<div class=\"border_1\">"
					+"<div class=\"border_2\">"													
						+"<div class=\"border_3\">"
							+"<div class=\"left_header\">"
								+"<div class=\"pad\">"
									+"<img src=\"images/icons/bullet_eee.gif\" style=\"margin-right:20px;\" />"
									+"<a href=\"page/cars_new_viewer/&id="+id+"\" title=\"View "+ model + " " + derivative + "\">"
										+ model + " " + derivative
									+"</a>"
								+"</div>"
							+"</div>"
							+"<div class=\"right_header\">"
								+"<div class=\"pad\">"
									+"&pound;"+ escapeHTML(price)
								+"</div>"
							+"</div>"
						+"</div>"
					+"</div>"		
					+"<div class=\"singlesearchresult\">"
						+"<div class=\"left\">"
							+"<a href=\"page/cars_new_viewer/&id="+id+"\" title=\" View "+model+" "+derivative+"\">"
								+"<img src=\""+image+"\" width=\"105px\" height=\"57px\"/>"
							+"</a>"
						+"</div>"
						+"<div class=\"right\">"
							+"<div class=\"left_item\">"
								+"<p class=\"item\">"
									+"Trim:"
								+"</p>"
								+"<p class=\"text\">"
									+ escapeHTML(trim)
								+"</p>"
								+"<div class=\"clearing\">"
								+"</div>"
							+"</div>"
							+"<div class=\"mid_item\">"
								+"<p class=\"item\">"
									+"Drivetrain:"
								+"</p>"
								+"<p class=\"text\">"
									+ escapeHTML(drivetrain)
								+"</p>"
								+"<div class=\"clearing\">"
								+"</div>"
							+"</div>"
							+"<div class=\"right_item\">"
								+"<p class=\"item\">"
									+"Fuel Type:"
								+"</p>"
								+"<p class=\"text\">"
									+ escapeHTML(fuel_type)
								+"</p>"
								+"<div class=\"clearing\">"
								+"</div>"
							+"</div>"
							+"<div class=\"left_item\">"
								+"<p class=\"item\">"
									+"Bodystyle:"
								+"</p>"
								+"<p class=\"text\">"
									+ escapeHTML(body)
								+"</p>"
								+"<div class=\"clearing\">"
								+"</div>"
							+"</div>"
							+"<div class=\"mid_item\">"
								+"<p class=\"item\">"
									+"Fuel Delivery:"
								+"</p>"
								+"<p class=\"text\">"
									+ escapeHTML(fuel_delivery)
								+"</p>"
								+"<div class=\"clearing\">"
								+"</div>"
							+"</div>"
							+"<div class=\"left_item\">"
								+"<p class=\"item\">"
									+"Doors:"
								+"</p>"
								+"<p class=\"text\">"
									+ escapeHTML(doors)
								+"</p>"
								+"<div class=\"clearing\">"
								+"</div>"
							+"</div>"
							+"<div class=\"mid_item\">"
								+"<p class=\"item\">"
									+"Transmission:"
								+"</p>"
								+"<p class=\"text\">"
									+ escapeHTML(transmission)
								+"</p>"
								+"<div class=\"clearing\">"
								+"</div>"
							+"</div>"
							+"<div class=\"clearing\">"
							+"</div>"
						+"</div>"
					+"</div>"
					+"<div class=\"clearing\">"
					+"</div>"
				+"</div>"
			+"</div>";
		}
		
		
		// Determine which part of the page to update
		if((from_source == "search") || (from_source == "ordering") || (from_source == "limit") || (from_source == "pager")){
			if(document.getElementById("viewer_page").value == 1){
				window.location.href="page/cars_new_search/";
			}
			else {
				// Update the car list in the html
				document.getElementById('car_list').innerHTML = responsetext;
				// Determine the number of results
				if(carArray.length == 1){
					num_cars = carArray.length + " Car";
				}
				else {
					num_cars = carArray.length + " Cars";
				}
				document.getElementById('max_cars').innerHTML = num_cars;
				
				if(carArray.length > (page_number * limit)){
					max_car_num = (page_number * limit);
				}
				else {
					max_car_num = carArray.length;
				}
				document.getElementById('max_car').innerHTML = max_car_num;
				
				document.getElementById('min_car').innerHTML = ((page_number-1) * limit) + 1;
				
				outputPager(page_number, max_pages);
			}
		}
		else {
			// Determine the number of results
			if(car_new_total == 1){
				num_cars = "<span style=\"font-weight:bold;\">" + car_new_total + "</span>" + " Car Matches";
			}
			else {
				num_cars = "<span style=\"font-weight:bold;\">" + car_new_total + "</span>" + " Cars Match";
			}
			
			// Update the number of cars
			document.getElementById("number_cars").innerHTML = "<p>" + num_cars + " your Criteria</p>";
			
			// Update the details of the select buttons
			updateSelect("range", response);
			updateSelect("model", response);
			updateSelect("transmission", response);
			updateSelect("fuel", response);
		}
	}
}