/*jshint asi: false, bitwise: true, boss: false, curly: true, debug: false, devel: false, eqeqeq: true, evil: false, forin: true, immed: true, laxbreak: false, newcap: true, noarg: true, noempty: true, nonew: true, nomen: true, onevar: true, plusplus: true, regexp: true, undef: true, sub: false, strict: true, white: false*/
/*global jQuery, console, baseUrl, window*/
(function ($) {
	"use strict";
	
	var $input, $results,
	    $container	=	$(".zoekOpStraat"),
	    dataUrl	=	baseUrl + "/straat";
	
	if ($container[0]) {
		$input		=	$container.find(".search");
		$results	=	$container.find(".results");
		
		$.getJSON(
			dataUrl,
			function (objects) {
				objects.sort(function (a, b) {
					var A	=	a.address.toLowerCase(),
					    B	=	b.address.toLowerCase();
					
					if(A > B) {
						return 1;
					}
					if(A < B) {
						return -1;
					}
					return 0;
				});
				
				$input.bind("keyup", function (e) {
					var i, url,
					    output	=	[],
					    value	=	new RegExp($(this).val(), "gi");
					
					if (e.keyCode === 13) {
						url	=	$results.find("a:first").attr("href");
						
						if (url) {
							window.location	=	url;
						}
					}
					
					if ($(this).val().length > 0) {
						for (i = 0; i < objects.length; i += 1) {
							if (objects[i].address.match(value)) {
								output.push('<li><a href="' + objects[i].url + '">' + objects[i].address + '</a></li>');
							}
						}
					}
					
					if (output.length === 0) {
						$results.hide();
					} else {
						$results.show();
					}
					
					$results.html(output.join(""));
				});
			}
		);
	}
	
}(jQuery));

