/*@cc_off @*/
/*@ alert('debug mode'); @*/
function params() {
	this.locid=0;
	this.beds=new Array();
	this.beds.remove=function(from,to)
	{
		var rest = this.slice((to || from) + 1 || this.length);
		this.length = from < 0 ? this.length + from : from;
		return this.push.apply(this, rest);
	};
	this.prices=new Array();
	this.prices.remove=function(from,to)
	{
		var rest = this.slice((to || from) + 1 || this.length);
		this.length = from < 0 ? this.length + from : from;
		return this.push.apply(this, rest);
	};
	this.date='';
	this.areas='';
	this.bills=0;
	this.setBeds=function(bed) {
		var search=this.beds.indexOf(bed);
		if (search>(-1)) this.beds.remove(search);
		else this.beds.push(bed);
	};
	this.setPrice=function(price) {
		var search=this.prices.indexOf(price);
		if (search>(-1)) this.prices.remove(search);
		else this.prices.push(price);
	};
	this.queryBeds=function() {
		if (this.beds.length>0)
		{
			var string=this.beds.join('&bed[]=');
			return string;
		}
		else return false;
	};
	this.queryPrices=function() {
		if (this.prices.length>0)
		{
			var string=this.prices.join('&price[]=');
			return string;
		}
		else return false;
	};
	this.venues=new Array();
	this.venues.remove=function(from,to)
	{
		var rest = this.slice((to || from) + 1 || this.length);
		this.length = from < 0 ? this.length + from : from;
		return this.push.apply(this, rest);
	};
	this.setVenue=function(venue) {
		var search=this.venues.indexOf(venue);
		if (search>(-1)) this.venues.remove(search);
		else this.venues.push(venue);
	};
	this.queryVenues=function() {
		if (this.venues.length>0)
		{
			var string=this.venues.join(',');
			return string;
		}
		else return false;
	};
	this.road='';
	this.exact=0;
	this.landlord=0;
	this.meta=new Array();
	this.clearMeta=function(){
		this.meta.length=0;
	};
	this.addMeta=function(meta){
		this.meta.push(meta);
	};
	this.queryMeta=function() {
		if (this.meta.length>0)
		{
			var string=this.meta.join('&meta[]=');
			return string;
		}
		else return false;
	};
}
var search=new params();
var boxes=new Array();
var year=new Array();
var display=0;
var blocks=0;
// used for road search
var last;
var previous;

// ajax stuff
function startSearch()
{
	$('ul.pages').empty();
	blocks=0;
	if (gmap) clearMarkers();
	if (gmap) gpoints.length=0;
	boxes.length=0;
}

function showHouse()
{
	startSearch();
	var query=new Array();
	var beds=search.queryBeds();
	if (beds) query.push("bed[]="+beds);
	var prices=search.queryPrices();
	if (prices) query.push("price[]="+prices);
	if (search.areas.length>0) query.push("area="+search.areas);
	if (search.bills==1) query.push("bills=1");
	if (search.exact>0) query.push("exact="+search.exact);
	if (search.road.length>0) query.push("road="+search.road);
	if (search.landlord>0) query.push("landlord="+search.landlord);
	if (query.length>0)
	{
		if (search.locid>0) query.push("loc="+search.locid);
		var meta=search.queryMeta();
		if (meta) query.push("meta[]="+meta);
		if (search.date.length>0) query.push("date="+search.date);
		query=query.join('&');
		ajaxHouse(query,false);
	}
	else
	{
		$.get("ajax_clear.php");
		if (gmap) gmap.clearMarkers();
		$('#results h3').text('searches reset');
		$('#houses').html('<p>Choose an area or click on the bed and price buttons to continue searching.</p>');
	}
}

function ajaxHouse(query,cache)
{
	/*@ alert('starting query with: '+query); @*/
	$.ajax({
		type:"GET",
		url:url+"ajax_search.php",
		dataType:"json",
		data: query,
		error: function(xhr,desc,exceptionobj){
			$('#houses').html('<p>Sorry, an error has occured and no houses could be found. Try refreshing the page if you keep seeing this message.</p>');
		},
		success:function(result){
			if (!result.error)
			{
				/*@ alert('query succeeded, displaying houses'); @*/
				var count=processHouses(result);
				if (count>0) displayHouses(1);
				if (cache)
				{
					$('#results > p').hide();
					/*@ alert('setting cache beds'); @*/
					for (var i in result.query.beds)
					{
						if (result.query.beds.hasOwnProperty(i))
						{
							$("div.button.beds > a[rel='"+result.query.beds[i]+"']").parent().addClass('selected');
							search.setBeds(result.query.beds[i]);
						}
					}
					/*@ alert('setting cache prices'); @*/
					for (var i in result.query.price)
					{
						if (result.query.price.hasOwnProperty(i))
						{
							$("div.button.price > a[rel='"+result.query.price[i]+"']").parent().addClass('selected');
							search.setPrice(result.query.price[i]);
						}
					}
					if (result.query.area.length>0)
					{
						/*@ alert('setting area'); @*/
						$('select.area').find("option[value='"+result.query.area+"']").attr('selected','selected');
						search.areas=result.query.area;
					}
					if (result.query.bills==1)
					{
						/*@ alert('setting bills'); @*/
						$('div.button.bills').addClass('selected');
						search.bills=1;
					}
				}
			}
		}
	});
}

function processHouses(result)
{
	var number='';
	if (result.count>0)
	{
		$('#houses').empty();
		/*@ alert('iterating houses'); @*/
		$.each(result.houses,function(i,house){
			html=miniHouse(house,year);
			boxes.push(html);
			if ((house.lat!=0) && (house.lng!=0) && (i<60))
			{
				if (gmap)
				{
					var icon;
					switch (house.icon)
					{
						case 'let':
							icon=iconLet;
							break;
						case 'unlet':
							icon=iconUnlet;
							break;
					}
					createMarker(house.lat,house.lng,html,icon);
				}
			}
			if (i==(display*blocks)) blocks++;
		});
		if (gmap) if (gpoints.length>0) fitMap(15);
		number=result.count;
	}
	else
	{
		$('#houses').html('<p>Sorry, no houses were found to match what you asked for.</p>');
		number='No ';
	}
	$('#results > div.box-h > div.box-h-r > h3').text(number+' results').addClass('short');
	return result.count;
}

function displayHouses(block)
{
	/*@ alert('creating output'); @*/
	var start=display*(block-1);
	var end=display*block;
	if (boxes.length<end) end=boxes.length;
	var output='';
	for (i=start;i<end;i++)
	{
		output+=boxes[i];
	}
	/*@ alert('adding shortlists'); @*/
	$(output).find('a.list').click(function(e){
		$(this).shortList();
		e.preventDefault();
	}).end().appendTo('#houses');
	/*@ alert('adding buttons'); @*/
	if (blocks>1)
	{
		var buttons=makeButtons(1);
		/*@ alert('buttons made'); @*/
		$('ul.pages').html(buttons);
		/*@ alert('adding onclick to buttons'); @*/
		$('ul.pages').find('li > a').click(function(){
			 $(this).seeResults(1);
		});
	}
}

function showBusiness()
{
	startSearch();
	var query=new Array();
	var venues=search.queryVenues();
	if (venues) query.push("venues="+venues);
	if (query.length>0)
	{
		if (search.locid>0) query.push("loc="+search.locid);
		query=query.join('&');
		ajaxBusiness(query,false);
	}
	else
	{
		$.get("ajax_clear.php");
		if (gmap) gmap.clearMarkers();
		$('#results > div.box-h > div.box-h-r > h3').text('searches reset');
		$('#houses').html('<p>Choose an area or click on the bed and price buttons to continue searching.</p>');
	}
}

function ajaxBusiness(query,cache)
{
	$.ajax({
		type:"GET",
		url:url+"ajax_business.php",
		dataType:"json",
		data: query,
		error: function(xhr,desc,exceptionobj){
			$('#houses').html('<p>Sorry, an error has occured and no businesses could be found. Try refreshing the page if you keep seeing this message.</p>');
		},
		success:function(result){
			var count=processBusiness(result);
			if (count>0) displayBusiness(1);
		}
	});
}

function processBusiness(result)
{
	$('#results > div.box-h > div.box-h-r > h3').text(result.count+' results').addClass('short');
	if (result.count>0)
	{
		var icon='';
		var html='';
		$.each(result.business,function(i,bus){
			html=miniBusiness(bus);
			boxes.push(html);
			if ((bus.lat!=0) && (bus.lng!=0) && (i<60))
			{
				if (gmap)
				{
					switch (bus.venue)
					{
						case 'Food':
							icon=iconFood;
							break;
						case 'Nightclub':
							icon=iconClub;
							break;
						case 'Hotel':
							icon=iconHotel;
							break;
						case 'Service':
							icon=iconService;
							break;
						case 'Shop':
							icon=iconShop;
							break;
					}
					createMarker(bus.lat,bus.lng,html,icon);
				}
			}
			if (i==(display*blocks)) blocks++;
		});
		if (gmap) if (gpoints.length>0) fitMap(15);
		number=result.count;
	}
	else
	{
		$('#houses').html('<p>Sorry, no businesses were found to match what you asked for.</p>');
		number='No ';
	}
	$('#results > div.box-h > div.box-h-r > h3').text(number+' results').addClass('short');
	return result.count;
}

function displayBusiness(block)
{
	/*@ alert('creating output'); @*/
	var start=display*(block-1);
	var end=display*block;
	if (boxes.length<end) end=boxes.length;
	var output='';
	for (i=start;i<end;i++)
	{
		output+=boxes[i];
	}
	$('#houses').html(output);
	/*@ alert('adding buttons'); @*/
	if (blocks>1)
	{
		var buttons=makeButtons(1);
		/*@ alert('buttons made'); @*/
		$('ul.pages').html(buttons);
		/*@ alert('adding onclick to buttons'); @*/
		$('ul.pages').find('li > a').click(function(){
			 $(this).seeResults(1);
		});
	}
}

function makeButtons(selected)
{
	var buttons='<li class="title">Pages</li>';
	/*@ alert('making buttons'); @*/
	if (blocks<=5)
	{
		/*@ alert('less than 5'); @*/
		for (i=1;i<=blocks;i++)
		{
			buttons+='<li';
			if (i==selected) buttons+=' class="selected"';
			buttons+='><a href="#page-'+i+'" rel="'+i+'">'+i+'</a></li>';
		}
	}
	else
	{
		if (selected<=2)
		{
			/*@ alert('start select'); @*/
			for (i=1;i<=3;i++)
			{
				buttons+='<li';
				if (i==selected) buttons+=' class="selected"';
				buttons+='><a href="#page-'+i+'" rel="'+i+'">'+i+'</a></li>';
			}
			buttons+='<li class="space">-</li><li><a href="#page-'+(blocks-1)+'" rel="'+(blocks-1)+'">'+(blocks-1)+'</a></li><li><a href="#page-'+i+'" rel="'+blocks+'">'+blocks+'</a></li>';
		}
		else if (selected>=(blocks-1))
		{
			/*@ alert('end select'); @*/
			buttons+='<li><a href="#page-1" rel="1">1</a></li><li><a href="#page-2" rel="2">2</a></li><li class="space">-</li>';
			for (i=(blocks-2);i<=blocks;i++)
			{
				buttons+='<li';
				if (i==selected) buttons+=' class="selected"';
				buttons+='><a href="#page-'+i+'" rel="'+i+'">'+i+'</a></li>';
			}
		}
		else
		{
			/*@ alert('middle select'); @*/
			buttons+='<li><a href="#page-1" rel="1">1</a></li><li class="space">-</li>';
			for (i=(selected-1);i<=(selected-(-1));i++)
			{
				buttons+='<li';
				if (i==selected) buttons+=' class="selected"';
				buttons+='><a href="#page-'+i+'" rel="'+i+'">'+i+'</a></li>';
			}
			buttons+='<li class="space">-</li><li><a href="#page-'+blocks+'" rel="'+blocks+'">'+blocks+'</a></li>';
		}
	}
	/*@ alert('returning buttons: '+buttons); @*/
	return buttons;
}

function roadSearch(name)
{
	$.getJSON(url+"ajax_roads.php",{name:name},function(roads){
		if (roads!=previous)
		{
			$('#roads').empty().show();
			$.each(roads,function(i,road){
				if (road.error)
				{
					$('#roads').hide();
				}
				else
				{
					var link=$('<a href="#" title="Click to search for houses on this road">'+road.name+'</a>').click(function(e){
						$("input[name='road']").val(road.name);
						$('#roads').hide();
						e.preventDefault;
					});
				}
				$('<li>').append(link).appendTo('#roads');
			});
			previous=roads;
		}
	});
}

function setupSearch()
{
	$('div.button.beds > a').click(function(e){
		$(this).bedSearch();
		e.preventDefault();
	});
	$('div.button.price > a').click(function(e){
		$(this).priceSearch();
		e.preventDefault();
	});
	
	$('fieldset.search').find('select.date').each(function(){
		var date=$(this).find("option:selected").val();
		search.date=date;
		$(this).change(function(){
			$(this).dateSearch();
		});
	});
	$('fieldset.search').find('select.area').change(function(){
		$(this).areaSearch();
	});
	$('div.button.bills > a').click(function(e){
		$(this).billSearch();
		e.preventDefault();
	});
	
	$('div.venue > a').click(function(){
		$(this).venueSearch();
	});
	
	$('div.advanced').hide().addClass('j');
	$('a.advanced').click(function(e){
		$('div.advanced').toggle();
		e.preventDefault();
	});
	$('#roads').hide();
	$('input[name="road"]').keyup(function(){
		var name=$(this).val();
		if ((name.length>2) && (name!=last))
		{
			last=name;
			roadSearch(name);
		}
		else
		{
			$('#roads').hide();
		}
	});
	$('input.submit').click(function(){
		$(this).advancedSearch();
	});
	search.locid=$('#locid').val();
}

$.fn.seeResults=function(current){
	var block=$(this).attr('rel');
	$('#houses').empty();
	displayHouses(block);
	var buttons=makeButtons(block);
	$('ul.pages').html(buttons);
	$('ul.pages').find('li > a').click(function(){
		 $(this).seeResults(block);
	});
};

$.fn.bedSearch=function(){
	var bed=$(this).attr('rel');
	bed=parseInt(bed);
	search.setBeds(bed);
	showHouse();
	//makeLink();
	$(this).parent().toggleClass('selected');
};

$.fn.priceSearch=function(){
	var price=$(this).attr('rel');
	price=parseInt(price);
	search.setPrice(price);
	showHouse();
	$(this).parent().toggleClass('selected');
};

$.fn.dateSearch=function(){
	var date=$(this).find("option:selected").val();
	search.date=date;
	showHouse();
};

$.fn.areaSearch=function(){
	var area=$(this).find("option:selected").text();
	var coords=$(this).find("option:selected").val();
	coords=coords.split(',');
	if (area=='Any') search.areas='';
	else search.areas=area;
	if (gmap) centreMap(coords[0],coords[1],coords[2]);
	showHouse();
};

$.fn.billSearch=function(){
	if (search.bills==1) search.bills=0;
	else search.bills=1;
	showHouse();
	$(this).parent().toggleClass('selected');
};

$.fn.venueSearch=function(){
	var venue=$(this).attr('rel');
	search.setVenue(venue);
	showBusiness();
	$(this).toggleClass('selected');
};

$.fn.advancedSearch=function(){
	$('div.advanced').fadeOut();
	search.road=$("input[name='road']").val();
	search.exact=$('input[name="exact"]').val();
	var landlord=$('select[name="landlord"]').val();
	search.landlord=landlord;
	search.clearMeta();
	$("input[name='meta[]']:checked").each(function(){
		search.addMeta($(this).val());
	});
	showHouse();
	/* scroll(0,0);
	window.location='#top'; */
};

$(document).ready(function(){
	display=$('#display').val();
	setupSearch();
});