var xmlhttp;
		
var types = [];
var typeString;
var brands = [];
var brandString;
var prices = [];
var priceString;

var page = 1;

function setPage(aPage){
	page = aPage;
	
	getCars();
}

function toggleNode(node){
	if(node.className == "option"){
		node.className = "option selected";
	} else {
		node.className = "option";
	}
}

function selectType(type,node){
	var index = types.indexOf(type);
	
	if(index<0){
		types[types.length] = type;
	} else {
		types.splice(index,1);
	}
	
	typeString = encodeURIComponent(types.join('~'));
	toggleNode(node);
	
	page = 1;
	
	getCars();
}

function selectBrand(brand,node){
	var index = brands.indexOf(brand);
	
	if(index<0){
		brands[brands.length] = brand;
	} else {
		brands.splice(index,1);
	}
	
	brandString = encodeURIComponent(brands.join('~'));
	toggleNode(node);
	
	page = 1;
	
	getCars();
}

function selectPrice(floor,ceiling,node){
	var index = prices.indexOf("(PRICE >= " + floor + " AND PRICE < " + ceiling + ")");
	
	if(index<0){
		prices[prices.length] = "(PRICE >= " + floor + " AND PRICE < " + ceiling + ")";
	} else {
		prices.splice(index,1);
	}
	
	priceString = encodeURIComponent(prices.join('~'));
	toggleNode(node);
	
	page = 1;
	
	getCars();
}

function getCars(){

	xmlhttp=GetXmlHttpObject();
	if (xmlhttp==null)	  {
		alert ("Browser does not support HTTP Request");
		return;
	}
	
	url = "cartable.php?";
	
	if(types!=""){
		url += "types=" + typeString + "&";
	}
	
	if(brands!=""){
		url += "brands=" + brandString + "&";
	}
	
	if(prices!=""){
		url += "prices=" + priceString + "&";
	}
	
	url += "page=" + page;
	
	xmlhttp.onreadystatechange=stateChanged;
	xmlhttp.open("GET",url,true);
	xmlhttp.send(null);
}

function GetXmlHttpObject(){
	if (window.XMLHttpRequest)	  {
		// code for IE7+, Firefox, Chrome, Opera, Safari
		return new XMLHttpRequest();
	}
	if (window.ActiveXObject)	  {
		// code for IE6, IE5
		return new ActiveXObject("Microsoft.XMLHTTP");
	}
	return null;
}

function stateChanged() {
	if (xmlhttp.readyState==4)	{
		document.getElementById("carTable").innerHTML=xmlhttp.responseText;
		
		$('a[name=mOpenner]').click(function(e) {
			//Cancel the link behavior
			e.preventDefault();
			
			
			//Get the A tag
			openModal($(this).attr('href'),true);
		});
		
		//select all the a tag with name equal to modal
		$('a[name=mDivOpenner]').click(function(e) {
			//Cancel the link behavior
			e.preventDefault();
			
			
			//Get the A tag
			openModal($(this).attr('href'));
		});
		
		//if mask is clicked
		$('#mask').click(function () {
			closeModal();
		});
		
		$('#carTable div.thumb').lightBox();

		
	} else {
		document.getElementById("carTable").innerHTML="<img src='images/loading.gif' style='width:64px;height:64px' alt='Loading...' />";
	}
}
