var num_areas = 1;
var max_areas = 5;

function less_bedrooms() {
	$('#maxbedrooms_select').val(-1);
	$('#morebedrooms').hide();
	$('.link_bedrooms').toggle();
}

function more_bedrooms() {
	$('#morebedrooms').show();
	$('.link_bedrooms').toggle();
}

function less_areas(i) {
	
	for (;i<num_areas;i++)
		$('#area_select'+i).val($('#area_select'+(i+1)).val());

	$('#area_select' + num_areas).val(0);
	$('#area' + (num_areas--)).hide();
	$('#link_moreareas').show();
}

function more_areas() {
	$('#area' + (++num_areas)).show();
	if (num_areas == max_areas)
		$('#link_moreareas').hide();
	else
		$('#link_moreareas').show();
}

function set_num_areas(i) {
	num_areas = i;	
}

function set_search_type(type) {
	$(type == 'area' ? '#search_areas' : '#search_postcodes').show();
	$(type == 'area' ? '#search_postcodes' : '#search_areas').hide();
}

// AJAX postcode verification ... //

pcode = {
		
	items: [],
	localSearch: new GlocalSearch(),
	insertPC: false,
	
	gResponse: function() {
		
		with (pcode) {
			
			if (localSearch.results[0]) {    
				
				var lat = localSearch.results[0].lat;
				var lng = localSearch.results[0].lng;
				
				if (insertPC) {
					var action = 'ipc';
					insertPC = false;
				} else {
					var action = 'upc';
				}
				
				$.post('/rankings/ajax/ylac-client.php?' + action, 'v=' + $('#postcode').attr('value') + 
					'&lat=' + lat + '&lng=' + lng, pcode.updateResponse, 'xml');	

			} else {
				$('#postcode_busy').hide();
				$('#postcode_msg').html('<span class="error">Not found</span>').show();	
			}
		}
	},
	
	isvalid: function(pc) {
		return /[a-zA-Z]{1,2}[0-9][0-9A-Za-z]?\s?[0-9][a-zA-Z]{2}/.test(pc);
	},
	
	keydown: function() {
		if (this.isvalid($('#postcode').attr('value'))) {
			$('#postcode_busy').show();
			$('#postcode_msg').hide();
			$.post('/rankings/ajax/ylac-client.php?cpc', '&v=' + $('#postcode').attr('value'), this.response, 'xml');	
		}
	},
	
	response: function(doc, status) {
		
		if (status != 'success') {
			alert(status);
			return;
		}
		
		var node = doc.firstChild.firstChild;
		var pc = node.firstChild.nodeValue;
		node = node.nextSibling;
		var location = node.firstChild.nodeValue;
		
		if (pc != 'yes' || location != 'yes') {
			
			if (pc != 'yes')
				pcode.insertPC = true;
			
			with (pcode) {
				localSearch.setSearchCompleteCallback(null, gResponse);
				localSearch.execute($('#postcode').attr('value') + ", UK");
			}
			
		} else {
			$('#postcode_busy').hide();	
			$('#postcode_msg').html('<span class="ok">OK!</span>').show();
		}
	
	},
	
	updateResponse: function(doc, status) {
		
		if (status != 'success') {
			alert(status);
			return;
		}
		
		var node = doc.firstChild.firstChild;
		var status = node.firstChild.nodeValue;
		
		$('#postcode_busy').hide();

		if (status == 'ok') {
			$('#postcode_msg').html('<span class="ok">OK!</span>').show();
		} 
		
	}

};