;(function($) {
	
// ensure the availability of console.log()
if (!window.console) window.console = { log: function() {} };
	
// ----------------------------------------------------------------------------
// Carousel
// ----------------------------------------------------------------------------	
$(function() {
	var carousel = $('.carousel');
	if (carousel.length) {
		var articles = carousel.find('.articles');
		var items = carousel.find('.articles ul li');
		var framewidth = items.filter(':first').outerWidth()+10;
		var index = 0;
	
		var button = carousel.find('.button');
		var scroll = function() {
			if (index == items.length -1 || index + 3 > items.length-1) { // rewind
				console.log('Rewind the console');
				articles.find('ul:first').animate({left: index = 0});
				button.removeClass('prev').addClass('next');
			}
			else {
				index += 3;
				index = Math.min(index, items.length-1);
				console.log('Move carousel to item', index);
				articles.find('ul:first').animate({left: -1*index*framewidth});
				if (index == items.length-1 || index + 3 > items.length-1)
					button.removeClass('next').addClass('prev');
			}
		}
	
		var buttonClicked = false;
		var timeoutInt = null;
	
		function timeout() {
			if (!buttonClicked) {
				timeoutInt = setTimeout(function() {
					scroll();
					timeout();
				}, 5000);
			}
		}
	
		timeout();
	
		button.click(function() {
			clearTimeout(timeoutInt);
			buttonClicked = true;
			scroll();
		});
	}
});

// ----------------------------------------------------------------------------
// Datepicker
// ----------------------------------------------------------------------------
$(function() {
	if (!window.datepicker_config)
		window.datepicker_config = {};
		
	window.datepicker_config = $.extend({
		changeMonth: true,
		changeYear: true,
		yearRange: '-110:100',
		monthNames: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
		monthNamesShort: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
		dayNamesMin: ['Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa'],
		onSelect: function(dateText, inst) {
			$(this).focus();
		}
	}, window.datepicker_config);
	
	$('input.datepicker').datepicker(window.datepicker_config);
});
	
// ----------------------------------------------------------------------------
// Superfish
// ----------------------------------------------------------------------------
$(function() {
	$('ul.sf-menu').supersubs({ 
		minWidth: 10, // minimum width of sub-menus in em units 
      	maxWidth: 40, // maximum width of sub-menus in em units 
		extraWidth: 1 // extra width can ensure lines don't sometimes turn over 
	}).superfish({
		//autoArrows: !($.browser.msie && $.browser.version == '6.0'),
		autoArrows: false,
		speed: 'fast',
		onShow: function() {
			$(this).prev('a').addClass('open');
		},
		onHide: function() {
			$(this).prev('a').removeClass('open');
		}
	});
});

// ----------------------------------------------------------------------------
// Single Location map
// ----------------------------------------------------------------------------
$(function() {
	if ((map = $('#location_map')).length) {
		console.log('Parsing location data from HTML');
		
		var address_clone = $('address:first').clone();
		address_clone.children('.ignore').remove();
		
		var location = {
			name: $('.location_name').text(),
			address: {
				text: address_clone.text(),
				html: $('address:first').html()
			},
			notes: $('.notes:first').text(),
			point: (function(coords) {
				if (coords) {
					var values = coords.split('/');
					return new GLatLng(values[0], values[1]);
				}
			})($('div.location_coords:first').text())
		};
		
		console.log('Blessing the Google Map');
		var map = new GMap2(map[0]);
		// washington, d.c. by default
		map.setCenter(new GLatLng(38.892091,-77.024055), 10);
		map.addControl(new GSmallZoomControl3D());
		
		function addLocation(loc) {
			console.log('Adding location', loc);
			var point = loc.point;
			if (point && point.lat() && point.lng()) {
				map.addOverlay(function() {
					var marker = new GMarker(loc.point);
					var link = 'http://maps.google.com/maps?f=q&source=s_q&hl=en&geocode=&q='+escape(loc.address.text)+'&z=12';
					marker.openInfoWindowHtml(
						'<div style="margin-bottom:4px;"><b style="font-size:14px;">'+$.trim(loc.name)+'</b> (<a href="'+link+'" target="_blank">Get Directions</a>)</div>' +
						loc.address.html +
						'<div><em>' + loc.notes + '</em></div>'
					);
					return marker;
				}());
				map.setCenter(point);
			}
		}
		
		if (!location.point) {
			new GClientGeocoder().getLatLng(location.address.text, function(point) {
				location.point = point;
				console.log(location.address.text, point);
				addLocation(location);
			});
		}
		else {
			addLocation(location);
		}
		
		
	}
})

// ----------------------------------------------------------------------------
// Large Locations map
// ----------------------------------------------------------------------------
$(function() {
	if ((map = $('#locations_map')).length && (list = $('div.locations ul')).length) {
		console.log('Parsing location data from HTML');
		var locations = [];
		
		$.each(list.find('li'), function(i, li) {
			var location = $(li);
			var address_clone = location.find('address:first').clone();
			address_clone.children('.ignore').remove();
			var model = {
				id: location.find('div.id:first').text(),
				name: location.find('.location_name').text(),
				address: {
					text: address_clone.text(),
					html: location.find('address:first').html()
				},
				phone: location.find('div.phone:first').text(),
				fax: location.find('div.fax:first').text(),
				show_metro: location.find('.metro:first').length,
				show_aquatic: location.find('.aquatic:first').length,
				show_childcare: location.find('.childcare:first').length,
				show_health_club: location.find('.health_club:first').length,
				notes: location.find('.notes:first').text(),
				point: (function(coords) {
					if (coords) {
						var values = coords.split('/');
						return new GLatLng(values[0], values[1]);
					}
				})(location.find('div.coords:first').text())
			};
			console.log(model.name, model.address.text, model.point);
			locations.push(model);
		});
		
		console.log('Blessing the Google Map');
		var map = new GMap2(map[0]);
		// washington, d.c. by default
		map.setCenter(new GLatLng(38.892091,-77.024055), 9);
		map.addControl(new GSmallZoomControl3D());
		
		var average = [];
		var centerTimeout = null;
		function addLocation(loc) {
			var point = loc.point;
			if (point && point.lat() && point.lng()) {
				map.addOverlay(function() {
					var marker = new GMarker(loc.point);
					var link = 'http://maps.google.com/maps?f=q&source=s_q&hl=en&geocode=&q='+escape(loc.address.text)+'&z=12';
					marker.bindInfoWindowHtml(
						'<div style="margin-bottom:4px;"><a href="/ci/the-jackson-clinics/home/locations/'+$.trim(loc.id)+'"><b style="font-size:14px;">'+$.trim(loc.name)+'</b></a> (<a href="'+link+'" target="_blank">Get Directions</a>)</div>' +
						'<div>' + loc.address.html + '</div>' +
						'<div><em>' + loc.notes + '</em></div>' +
						'<div style="float:left; margin-right:1em;">'+loc.phone+'</div>' +
						'<div>'+loc.fax+'</div>'
					);
					return marker;
				}());
				average.push({lat: point.lat(), long: point.lng()});
				
				// we use a timeout here to delay centering
				// because we don't know when geocoding (below)
				// will complete
				clearTimeout(centerTimeout);
				centerTimeout = setTimeout(function() {
					map.setCenter(averageCenter(), 9);
				}, 1000);
			}
		}
		
		function averageCenter() {
			var alat = 0;
			var along = 0;
			$.each(average, function(i, point) {
				alat += point.lat;
				along += point.long;
			});
			
			return new GLatLng(alat/average.length, along/average.length);			
		}
		
		var geocoder = new GClientGeocoder();
		$.each(locations, function(i, loc) {
			if (!loc.point) {
				console.log("Geocoding "+loc.address.text);
				geocoder.getLatLng(loc.address.text, function(point) {
					loc.point = point;
					console.log(loc.address.text, point);
					addLocation(loc);
				});
			}
			else {
				addLocation(loc);
			}
		});
		
	}
});

// ----------------------------------------------------------------------------
// Fancy boxes
// ----------------------------------------------------------------------------
$(function() {
	$('.fancy').fancybox();
	
	$('a.bio').fancybox({
		frameWidth: 640,
		frameHeight: 350
	})
	
});

})(jQuery);

// ----------------------------------------------------------------------------
// Field debugging
// ----------------------------------------------------------------------------
;(function($) {
	$.debugForms = function() {
		// text field values = text field name
		$.each($("input[type='text']"), function(i, input) {
			var field = $(input);
			field.val(field.attr('name'));
		});
		
		// textarea values = field name + Lorem Ipsum text
		$.each($('textarea'), function(i, textarea) {
			var field = $(textarea);
			field.val(field.attr('name') + 'Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.');
			field.after("<span>"+field.attr('name')+"</span>");
		});
		
		// select field value = first option with non-empty value
		$.each($('select'), function(i, select) {
			var field = $(select);
			$.each(select.options, function(i, option) {
				if (!select.selectedIndex && option.value != '')
					select.selectedIndex = 1;
			});
			field.after("<span>"+field.attr('name')+"</span>");
		});
		
		// checkboxes = checked
		$.each($("input[type='checkbox']"), function(i, checkbox) {
			var field = $(checkbox);
			checkbox.checked = true;
			field.after("<span>"+field.attr('name')+"</span>");
		});
		
		// radio buttons = last checked
		$.each($("input[type='radio']"), function(i, radio) {
			var field = $(radio);
			radio.checked = true;
			field.after("<span>"+field.attr('name')+"</span>");
		});
	};
	
	$(function() {
		//$.debugForms();
	});
})(jQuery);

// ----------------------------------------------------------------------------
// Info boxes on location featurette
// ----------------------------------------------------------------------------
;(function($) {
	$(function() {
		$('.location_featurette a.reveal').click(function() {
			$(this).parent().siblings('.description').toggle();
		});
	});
})(jQuery);

