 import UIKit
 import CoreLocation
 
-class LotlistViewController: UITableViewController, CLLocationManagerDelegate {
+class LotlistViewController: UITableViewController, CLLocationManagerDelegate, UISearchBarDelegate, UISearchControllerDelegate, UISearchResultsUpdating {
 
 	let locationManager = CLLocationManager()
 
-	// Store the single parking lots once they're retrieved from the server
-	// a single subarray for each section
+	var searchController: UISearchController!
+
 	var parkinglots: [Parkinglot] = []
 	var defaultSortedParkinglots: [Parkinglot] = []
+	var filteredParkinglots: [Parkinglot] = []
 	var sectionNames: [String] = []
 
 	override func viewDidLoad() {
 		super.viewDidLoad()
+
+		// Set up the UISearchController
+		searchController = UISearchController(searchResultsController: nil)
+		searchController.searchResultsUpdater = self
+		searchController.searchBar.delegate = self
+		searchController.dimsBackgroundDuringPresentation = false
+		searchController.hidesNavigationBarDuringPresentation = false
+		searchController.searchBar.searchBarStyle = UISearchBarStyle.Minimal
+
+		searchController.searchBar.frame = CGRectMake(searchController.searchBar.frame.origin.x, searchController.searchBar.frame.origin.y, searchController.searchBar.frame.size.width, 44.0)
+
+		tableView.tableHeaderView = searchController.searchBar
 
 		// set CLLocationManager delegate
 		locationManager.delegate = self

		updateData()
	}

	// MARK: - UITableViewDataSource

	override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
		return 1
	}

	override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
		return parkinglots.count
	}

	override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
		var cell: ParkinglotTableViewCell = tableView.dequeueReusableCellWithIdentifier("parkinglotCell") as! ParkinglotTableViewCell

		let thisLot = parkinglots[indexPath.row]

		cell.parkinglotNameLabel.text = thisLot.name
		cell.parkinglotLoadLabel.text = "\(thisLot.free)"

	override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
		if segue.identifier == "showParkinglotMap" {
			let indexPath = tableView.indexPathForSelectedRow()

			let selectedParkinglot: Parkinglot!
			if searchController.active {
				selectedParkinglot = filteredParkinglots[indexPath!.row]
			} else {
				selectedParkinglot = parkinglots[indexPath!.row]
			}

			let mapVC: MapViewController = segue.destinationViewController as! MapViewController
			mapVC.detailParkinglot = selectedParkinglot
			mapVC.allParkinglots = parkinglots
