$(function() {

	// Accordion

	window.accordion = {
		current: false,

		open: function(id) {			
			if (this.current == id) return this.close();
			
			this.close();
			$('#'+id+"_content").fadeIn();
			this.current = id;
		},

		close: function() {
			if (!this.current) return;
			$('#'+this.current+"_content").hide();
			this.current = false;
		}
	};
	
	$('.acc-title').click(function(e){ window.accordion.open(e.target.id); });

	// Google Maps
	
	window.googleMaps = {
		map: false,
		geocoder: false,
		marker: false,
		
		init: function(element_id) {
			googleMaps.geocoder = new google.maps.Geocoder();
			var myOptions = {
				zoom: 14,
				mapTypeId: google.maps.MapTypeId.ROADMAP,
				disableDefaultUI: true
		   };
		   googleMaps.map = new google.maps.Map(document.getElementById(element_id), myOptions);
		},

		geocode: function(address, fn) {
			if (!googleMaps.geocoder) return;
			googleMaps.geocoder.geocode({'address': address}, function(results, status) {
				if (!fn) return;
				if (status == google.maps.GeocoderStatus.OK) fn.call(this, results[0].geometry.location);
				else fn.call(this, false);
	     	});
		},

		setMarker: function(location) {
			if (googleMaps.marker) googleMaps.marker.setMap(null);
			googleMaps.marker = new google.maps.Marker({
				map: googleMaps.map, 
				position: location
			});
			googleMaps.map.setCenter(googleMaps.marker.getPosition());
			googleMaps.map.panTo(googleMaps.marker.getPosition());
		}
	};

	// Vendor search
	
	window.vendors = {
		results: false,
		detail: false,
		map: false,
		resultError: false,
		resultsBox: false,
		detailBox: false,
		
		init: function(pResults, pDetail, pMap, pResultError, pResultsBox, pDetailBox) {
			results = $('#'+pResults);
			detail = $('#'+pDetail);
			map = $('#'+pMap);
			resultError = $('#'+pResultError);
			resultsBox = $('#'+pResultsBox);
			detailBox = $('#'+pDetailBox);
			googleMaps.init(pMap);
		},
		
		search: function(address, type) {
			results.empty();
			detail.empty();
			resultsBox.css('display', 'block');
			detailBox.css('display', 'none');
			map.css('display', 'none');
			googleMaps.geocode(address, function(res) {
				if (!res) {
					resultError.css('display', 'block');
					return;
				}
				$.ajax({
					url: 'site/php/vendors.php',
					data: {lat: res.lat(), lng: res.lng(), type: type},
					dataType: 'json',
					error: function(request, textStatus, errorThrown) {
						resultError.css('display', 'block');
					},
					success: function(data, textStatus, request) {
						resultError.css('display', 'none');
						for (var i=0; i<data.length; i++) vendors.addVendor(data[i]);
					}
				});
			});
		},
		
		addVendor: function(dta) {
			elem = $('<div class="result">'+dta['name']+'</div>');
			elem.click(function(e) {
				detail.html(dta['info']);
				googleMaps.setMarker(new google.maps.LatLng(dta['x'], dta['y']));
				detailBox.css('display', 'block');
				map.css('display', 'block');
			})
			results.append(elem);
		}
	}

});