// Listings Per Page
/* 

author: scott lenger
last updated: February 2008

instructions:
because the listings dropdown is more of a feature, than a necessity, this script takes the simplified approach of only showing the option when javascript is available, or displaying a *requires javascript* message if both css and javascript conditions are not met.

1. add <head> link to this file
2. add <head> link to ajax.js file 
3. add #listings_per_page {display:none;} to stylesheet
4. add listingsPerPage(); function to onload (and any ajax content where the listings are recreated)
5. make dropdown form id="listings_per_page"
6. make select id="listings_page"

todo: remove the uneccesary onchange from the xhtml
*/

function listingsPerPage() {
	// define some global variables
	var selected = "";
	var url = "";
	var thestring = "";
	
	// test if item exists
	if (!document.getElementById("listings_per_page")) {return;}
	
	// display item (sets wrapper div to display:block;)
	document.getElementById("listings_per_page").style.display = "block";

	// remove javascript warning element if it exists
	if (document.getElementById("nojavascript")) { // test for the id (it is removed from the process.php as ajax capability is assumed if that file is present)
		var child = document.getElementById("nojavascript");
		child.parentNode.removeChild(child);
	}

	// add onchange function to the paginate dropdown
	document.getElementById("listings_page").onchange = function() {

		// find which option in the select dropdown was chosen and grab the text value
		var selectDropdown = document.getElementById("listings_page");
		selectDropdown.getElementsByTagName("option"); // get the options

		for (i=0; i<selectDropdown.length; i++) {
			if (selectDropdown[i].selected == "1") { // find the selected option

				selected = selectDropdown[i].text; // get the selected option text
			}
		}
		
		// get inputs with type="hidden"
		var gethidden = document.getElementById("listings_per_page");
		gethidden.getElementsByTagName("input"); // get all the forms inputs

		//
		
		for (i=0; i < gethidden.length; i++) {
			if (gethidden[i].type == "hidden") { // find the hidden inputs (which contain the query strings)

				thestring += "&" + gethidden[i].name + "=" + encodeURIComponent(gethidden[i].value); // encodeURIComponent replaces characters with UTF-8 encoding
	
				var url = "/scripts/vehicle-search-results-process.php?query=&perpage=" +selected + thestring; // switch the page url to the ajax results include file
			}
		}

		updateResults(url); // send url to update function
		displayLoading(); // show loading image (technically the content isn't loading until the ajax request is initiated (updatedResults(url)) but for usability purposes this shows that something is happening.

		return !updateResults(url); // cancels refresh if browser doesn't support ajax
	}
}