var availability;

function makeSlug(slugcontent)
{
    // convert to lowercase (important: since on next step special chars are defined in lowercase only)
    slugcontent = slugcontent.toLowerCase();
    // convert special chars
    var   accents={a:/\u00e1/g,e:/u00e9/g,i:/\u00ed/g,o:/\u00f3/g,u:/\u00fa/g,n:/\u00f1/g}
    for (var i in accents) slugcontent = slugcontent.replace(accents[i],i);

	var slugcontent_hyphens = slugcontent.replace(/\s/g,'-');
	var finishedslug = slugcontent_hyphens.replace(/[^a-zA-Z0-9\-]/g,'');
    finishedslug = finishedslug.toLowerCase();
    return finishedslug;
}


function showAvailable(num) {
	jQuery("#eddie").hide();
	var list = '<ul>';
	jQuery.each(availability, function(i,space) {
		jQuery.each(space, function(j,item) {
			if (num >= item.people.min && num <= item.people.max) {
				list += '<li><a href="http://www.lingfieldpoint.co.uk/spaces/' + makeSlug(i) + '">' + i + '</a> - ' + j + ' (' + item.people.min + '-' + item.people.max + ' people)</li>';
			}
		});
	});
	if (list == '<ul>') {
		list += '<li><a href="contact">Get in touch</a> and see what we can provide for you!</li>';
	}
	list += '</ul>';
	jQuery("#peoplecounterresults").empty().append(list);
}

var keydowntimeout;

jQuery(function() {
	jQuery.getJSON("http://www.lingfieldpoint.co.uk/availability.json", function(data) {
		availability = data;
		jQuery("#peoplecount").keydown(function(e) {
			clearTimeout(keydowntimeout);
			keydowntimeout = setTimeout(function() { showAvailable(e.target.value)},500);
		});
		jQuery("#peoplecount").removeAttr("disabled").focus().val("0");
	});
});
