var Local = {

    onCommentReply: function(id) {
		Comments.openReply(id);
	},

    onCancelReply: function(id) {
		Comments.closeReply();
	}

};

var wt = {}; // This is the setup for the webtools namespace

(function() { // This is where jQuery code can safely go without foobarring prototype
	var $ = jQuery;
	var g = google;
	
	$(document).ready(function() { // These functions get called on DOM ready
		if(wt.browserSucks && typeof correct_png == 'function') {
			correct_png();
		}
		$('a').click(function() { $(this).blur() }) // prevents outlines on links for IE
		wt.hero() // Crossfades hero shots if applicable
		wt.subnav();
		wt.carousel();
	})
	
	$(window).load(function() { // These functions get called when everything has loaded
		wt.maps();
	})
	
	wt.formDefaults = function() { // Swaps default text form input values to blank on focus and back to default text on blur
		$('input:text,textarea').each(function() {
			var elem = $(this)
			var defaultText = elem.val()
			elem.focus(function(){
				if(elem.val() == defaultText) {
					elem.val('')
				}
			})
			elem.blur(function(){
				if(elem.val() == '') {
					elem.val(defaultText)
				}
			})
		})
	}

	wt.hero = function() { // Heroshot crossfader; set options below this function

		if(!$('#imageFadeContainer').size()) {
			return
		}
		
		wt.hero.interval = null
		
		wt.hero.container = $('#imageFadeContainer')

		var fade = wt.hero.container.find('input[name=fadevalue]')
		wt.hero.fade = fade.val() * 1000
		fade.remove()
		
		var dur = wt.hero.container.find('input[name=showvalue]')
		wt.hero.dur = dur.val() * 1000
		dur.remove()
		
		if(wt.hero.useForeground) {
			wt.hero.container.append(
				$(jQuery('<div />')).attr({id: 'hero-foreground'})
			)
		}
			
		if(wt.hero.useCaptions) {
			if(wt.hero.container.children('a:first-child').size()) {
				var firstCaption = wt.hero.container.children('a:first-child').children('img').attr('alt')
			} else if(wt.hero.container.children('img:first-child').size()) {
				var firstCaption = wt.hero.container.children('img:first-child').attr('alt')
			} else {
				var firstCaption = ''
			}

			wt.hero.container.append(
				$(jQuery('<div />'))
					.attr({id: 'hero-caption'})
					.append(
						$(jQuery('<span />'))
							.attr({id: 'caption-holder'})
							.show()
							.text(firstCaption)
					)
			)
		}

		if(wt.hero.container.children('a,img').size() < 2) { // Less than two images, we don't need to xfade or add controls
			return
		}
		
		if(wt.hero.useControls) {
			wt.hero.container.append(
					$(jQuery('<div />'))
						.attr({id: 'hero-controls'})
						.append(
							$(jQuery('<ul />'))
								.append(
									$(jQuery('<li />'))
										.append(
											$(jQuery('<a />'))
												.attr({
													title: 'Previous Photo',
													id: 'hero-previous',
													href: '#previous-photo'
												})
												.click(function(c){
													c.preventDefault()
													clearInterval(wt.hero.interval)
													wt.hero.rotate('prev')
													$('#hero-pause').hide()
													$('#hero-play').show()
												})
										)
								)
								.append(
									$(jQuery('<li />'))
										.append(
											$(jQuery('<a />'))
												.attr({
													title: 'Pause Photos',
													id: 'hero-pause',
													href: '#pause-photos'
												})
												.click(function(c){
													c.preventDefault()
													clearInterval(wt.hero.interval)
													$('#hero-pause').hide()
													$('#hero-play').show()
												})
												.css({display: 'block'})
												.show()
										)
								)
								.append(
									$(jQuery('<li />'))
										.append(
											$(jQuery('<a />'))
												.attr({
													title: 'Play Photos',
													id: 'hero-play',
													href: '#play-photos'
												})
												.click(function(c){
													c.preventDefault()
													wt.hero.interval = setInterval(function(){
														wt.hero.rotate('next')
													}, wt.hero.dur + wt.hero.fade)
													$('#hero-pause').show()
													$('#hero-play').hide()
												})
												.css({display: 'block'})
												.hide()
										)
								)
								.append(
									$(jQuery('<li />'))
										.append(
											$(jQuery('<a />'))
												.attr({
													title: 'Next Photo',
													id: 'hero-next',
													href: '#next-photo'
												})
												.click(function(c){
													c.preventDefault()
													clearInterval(wt.hero.interval)
													wt.hero.rotate('next')
													$('#hero-pause').hide()
													$('#hero-play').show()
												})
										)
								)
						)
				)
		}
			
			
		wt.hero.container.children('a:first-child,img:first-child').attr({current: 'current'})
		wt.hero.container.children('a:not(:first-child),img:not(:first-child)').hide()
		if(jQuery.browser.safari) {
			wt.hero.container.children('a:not(:first-child),img:not(:first-child)').css({display: 'none'})
		}

		wt.hero.interval = setInterval(function() {
			wt.hero.rotate('next')
		}, wt.hero.dur + wt.hero.fade)

		wt.hero.rotate = function(dir) {
			if(typeof dir == 'undefined') {
				var dir = 'next'
			}
			var images = wt.hero.container.children('a,img')
			var current = wt.hero.container.children('a[current],img[current]')
			if(dir == 'next') {
				if(current.next('a,img').size()) {
					var to = current.next('a,img')
				} else {
					var to = $(images[0])
				}
			} else {
				if(current.prev('a,img').size()) {
					var to = current.prev('a,img')
				} else {
					var to = $(images[images.size() - 1])
				}
			}

			current.removeAttr('current').fadeOut(wt.hero.fade)
			
			if(wt.hero.useCaptions) {
				wt.hero.container.find('#caption-holder').fadeOut(wt.hero.fade / 2, function(){
					wt.hero.container.find('#caption-holder').text(to.find('img').size() ? to.find('img').attr('alt') : to.attr('alt'))
					wt.hero.container.find('#caption-holder').fadeIn(wt.hero.fade / 2)
				})
			}

			if(wt.hero.useForeground) {
				if(to.href != 'undefined') {
					wt.hero.container.find('#hero-foreground').bind('click',function() {
						window.location = to.href
					})
				} else {
					wt.hero.container.find('#hero-foreground').unbind('click',function() {
						window.location = to.href
					})
				}
			}
			to.attr({current: 'current'}).fadeIn(wt.hero.fade)
		}
	}

	// Heroshot options
	wt.hero.useForeground = true
	wt.hero.useControls = true
	wt.hero.useCaptions = true
	
	wt.subnav = function() {
		var tabs = $('#subnav ul.subnav li');

		if($('html#locations').size()) {
			var ajaxTemp = $(jQuery('<div id="ajax-temp-subnav" style="position: absolute; top: -100000px; left: -100000px;"></div>'));
			$('body').append(ajaxTemp);
			ajaxTemp.ajaxComplete(function() {
				$('#hd_2 .wrapper:not(:visible)').slideDown('normal');
				$('#hd_2 .map:visible').slideUp('normal');
				$('.locations').show().removeAttr('use');
				var currentContent = $('#hd_2').find('.wrapper');
				if($('#hd_2 .map').is(':visible')) {
					currentContent.remove();
					var newContent = ajaxTemp.find('.wrapper')
					newContent.css({'display':'none'});
					newContent.appendTo($('#hd_2'));
					newContent.slideDown('normal', function() {
					});
				} else {
					currentContent.slideUp(
						'normal',
						function() {
							currentContent.remove();
							var newContent = ajaxTemp.find('.wrapper')
							newContent.css({'display':'none'});
							newContent.appendTo($('#hd_2'));
							newContent.slideDown('normal', function() {
							});
						}
					);
				}
			});
			tabs.each(function() {
				var tab = $(this);
				var link = tab.find('a');
				link.click(function(c) {
					c.preventDefault();
					if(tab.is('.current')) {
						return false;
					}

					tabs.filter('.current').removeClass('current');
					tab.addClass('current');
					ajaxTemp.load(
						link.attr('href') + ' #hd_2 .wrapper',
						{},
					 	function(){
					    	// The ajaxComplete function up top should handle this part
						}
					);

				});
			});
		} else if($('div.locations').size()) {
			origHeight = $('#hd_2').height();
			tabs.filter('.images').find('a').click(function(c) {
				c.preventDefault();
				tabs.filter('.current').removeClass('current');
				$(this).parent('li').addClass('current');
				$('#hd_2 .wrapper .map:visible').slideUp('normal');
				if(wt.browserSucks) { $('#hd_2').animate({'height': origHeight}); }
				$('#hd_2 .wrapper .pics').slideDown('normal');
			}).click();
			tabs.filter('.map').find('a').click(function(c) {
				c.preventDefault();
				tabs.filter('.current').removeClass('current');
				$(this).parent('li').addClass('current');
				$('#hd_2 .wrapper .pics:visible').slideUp('normal');
				if(wt.browserSucks) { $('#hd_2').animate({'height':'374px'}); }
				$('#hd_2 .wrapper .map').slideDown('normal', function() { setTimeout(function() { wt.maps.map.checkResize(); },100); });
			});
		}
		
		tabs.eq(0).addClass('current');
	}
	
	wt.carousel = function() {
		var containers = $('div.pics');
		containers.each(function() {
			var container = $(this);
			var images = container.find('img');
			container.empty().append(images).addClass('scripted');
			images.each(function() {
				var image = $(this);
				var prev = image.prev('img').size() ? image.prev('img') : images.eq(images.size() - 1);
				var next = image.next('img').size() ? image.next('img') : images.eq(0);
				if(images.size() > 3) {
					var prevPrev = prev.prev('img').size() ? prev.prev('img') : images.eq(images.size() - 1);
					var nextNext = next.next('img').size() ? next.next('img') : images.eq(0);
				} else {
					var prevPrev = false;
					var nextNext = false;
				}
				var everythingElse = image.next('img').next('img').nextAll('img').add(image.prev('img').prev('img').prevAll('img'));
				
				image.click(function() {
					if(image.is(':animated')) { return; }
					everythingElse.hide();
					image.add(prev).add(next).show();
					image.css({'z-index':3}).animate({
						'top': 0,
						'left': (Math.round(container.width() / 2) - 189) + 'px',
						'height': '198px',
						'width': '378px',
						'opacity': 1
					},'normal');
					prev.css({'z-index':2}).animate({
						'width': '310px',
						'height': '162px',
						'left': 0,
						'top': '18px',
						'opacity': 0.5
					},'normal');
					if(prevPrev) {
						prevPrev.show().css({'z-index':1}).animate({
							'width': '310px',
							'height': '162px',
							'left': 0,
							'top': '18px',
							'opacity': 0
						},'normal');
					}
					next.css({'z-index':2}).animate({
						'width': '310px',
						'height': '162px',
						'left': (container.width() - 325) + 'px',
						'top': '18px',
						'opacity': 0.5
					},'normal');
					if(nextNext) {
						nextNext.show().css({'z-index':1}).animate({
							'width': '310px',
							'height': '162px',
							'left': (container.width() - 325) + 'px',
							'top': '18px',
							'opacity': 0
						},'normal');
					}
				});
			});
			
			images.eq(0).click();
			
		});
	}
	
	wt.maps = function() {
		if(!$('div.locations').size()) { return; }
		wt.maps.init();
		wt.maps.addLocations();
	}
	
	wt.maps.init = function() {
		wt.maps.map = new g.maps.Map2(document.getElementById('map')); // Set up the map
		wt.maps.map.addControl(new g.maps.SmallMapControl()) // Use the simple pan/zoom controls
//		wt.maps.map.enableScrollWheelZoom() // Allow zooming via mouse scrollwheel
		wt.maps.map.setCenter(new g.maps.LatLng(35,-85),10) // Init the map and set it to show the whole world
		wt.maps.map.bounds = new g.maps.LatLngBounds() // Set the initial map boundaries
		wt.maps.geocoder = new g.maps.ClientGeocoder() // Init the geocoder
		wt.maps.manager = new g.maps.MarkerManager(wt.maps.map) // Start the marker manager
		wt.maps.icons = {};
		wt.maps.icons.normal = new g.maps.Icon(G_DEFAULT_ICON);
		wt.maps.icons.normal.shadow = "http://www.google.com/mapfiles/shadow50.png";
		wt.maps.icons.normal.iconSize = new g.maps.Size(20, 34);
		wt.maps.icons.normal.shadowSize = new g.maps.Size(37, 34);
		wt.maps.icons.normal.iconAnchor = new g.maps.Point(9, 34);
		wt.maps.icons.normal.infoWindowAnchor = new g.maps.Point(9, 2);
		wt.maps.icons.arrow = new g.maps.Icon(G_DEFAULT_ICON);
		wt.maps.icons.arrow.image = 'http://www.google.com/mapfiles/arrow.png';
		wt.maps.icons.arrow.shadow = 'http://www.google.com/mapfiles/arrowshadow.png';
		wt.maps.icons.arrow.iconSize = new g.maps.Size(39, 34);
		wt.maps.icons.arrow.shadowSize = new g.maps.Size(39, 34);
		wt.maps.icons.arrow.iconAnchor = new g.maps.Point(9, 34);
		wt.maps.arrows = new Array();

		$('form.find-location-near-you').submit(function(s) {
			s.preventDefault();
			wt.maps.nearbySearch($('input[name=zip]').val());
		});
		$('body').ajaxComplete(function() {
			$('form.find-location-near-you').submit(function(s) {
				s.preventDefault();
				wt.maps.nearbySearch($('input[name=zip]').val());
			});
		})
	}
	
	wt.maps.letteredIcon = function(count) {
		var alphabet = new Array();
		alphabet[0] = "A"; alphabet[1] = "B"; alphabet[2] = "C"; alphabet[3] = "D"; alphabet[4] = "E"; alphabet[5] = "F"; alphabet[6] = "G"; alphabet[7] = "H"; alphabet[8] = "I"; alphabet[9] = "J"; alphabet[10] = "K"; alphabet[11] = "L"; alphabet[12] = "M"; alphabet[13] = "N"; alphabet[14] = "O"; alphabet[15] = "P"; alphabet[16] = "Q"; alphabet[17] = "R"; alphabet[18] = "S"; alphabet[19] = "T"; alphabet[20] = "U"; alphabet[21] = "V"; alphabet[22] = "W"; alphabet[23] = "X"; alphabet[24] = "Y"; alphabet[25] = "Z";
		var icon = new g.maps.Icon(wt.maps.icons.normal);
		icon.image = 'http://www.google.com/mapfiles/marker' + alphabet[count] + '.png';
		
		return icon;
	}
	
	wt.maps.addLocations = function(pin) {
		if($('html#locations').size()) {
			wt.maps.locations = $('.location[data-lat][data-lon]');
			wt.maps.map.clearOverlays();
			if(typeof pin != 'undefined') {
				var marker = new g.maps.Marker(pin,{'icon': new g.maps.Icon(wt.maps.icons.arrow)});
				wt.maps.arrows[wt.maps.arrows.length] = marker;
				wt.maps.map.addOverlay(marker);
				wt.maps.map.bounds.extend(pin);
				wt.maps.map.setCenter(pin,13);
			}
			wt.maps.locations.each(function(i) {
				var location = $(this);
				if(location.is(':not([use])')) { return; }
				var point = new g.maps.LatLng(location.attr('data-lat'),location.attr('data-lon'));
				if(point.x && point.y) {
					var marker = new g.maps.Marker(point,{icon: wt.maps.letteredIcon(i)});
					wt.maps.map.addOverlay(marker);
					var description = '<strong>' + location.find('.title').text() + '</strong><br /><a href="' + location.find('a.rates_button').attr('href') + '">View Details</a> <a href="' + location.find('.directions').attr('href') + '" target="_blank">Get Directions</a><br /><br />'
					google.maps.Event.addListener(marker, 'click', function() {
						marker.openInfoWindowHtml(description);
					})
					if(wt.maps.locations.size() == 1 || i == 0) {
						wt.maps.map.setCenter(point,13);
					}
					wt.maps.map.bounds.extend(point);
				}
			});
			setTimeout(function() {
				var center = wt.maps.map.bounds.getCenter();
				if(wt.maps.map.getBoundsZoomLevel(wt.maps.map.bounds) - 1 != wt.maps.map.getZoom()) {
					wt.maps.map.setCenter(center, wt.maps.map.getBoundsZoomLevel(wt.maps.map.bounds) - 1);
				} else {
					wt.maps.map.panTo(center);
				}
			},100);
		} else if($('div.locations').size()) {
			$('#subnav li.map a').click(function() {
				wt.maps.map.clearOverlays();
				var point = new g.maps.LatLng($('#bd h2[data-lat]').attr('data-lat'),$('#bd h2[data-lat]').attr('data-lon'));
				if(point.x && point.y) {
					var marker = new g.maps.Marker(point);
					wt.maps.map.addOverlay(marker);
					var description = '<strong>' + $('#bd h2').text() + '</strong><br /><a href="http://maps.google.com/maps?q=' + $('#bd h2').text() + '" target="_blank">Get Directions</a><br /><br />'
					google.maps.Event.addListener(marker, 'click', function() {
						marker.openInfoWindowHtml(description);
					})
					setTimeout(function() {
						wt.maps.map.setCenter(point,13);
//						wt.maps.map.panTo(point);
						wt.maps.map.checkResize();
					},1000)
				}
			});
		}
		wt.maps.map.checkResize();
	}
	
	wt.maps.nearbySearch = function(location) {
		if(!wt.maps.geocoder) { return false; }
		$('#hd_2 .wrapper:visible').slideUp('normal');
		$('#hd_2 .map:not(:visible)').slideDown('normal', function() {
			wt.maps.locations.removeAttr('use');
			wt.maps.geocoder.getLatLng(
				location,
				function(point) {
					if(point) {
						var locations = new Array();
						var passthroughLocations = new Array();
						wt.maps.locations.each(function() {
							var location = $(this);
							location.removeAttr('use').show();
							if(location.attr('data-lat') && location.attr('data-lon')) {
								var distance = point.distanceFrom(new g.maps.LatLng(location.attr('data-lat'),location.attr('data-lon')));
								if(distance < 160935) {
									locations[locations.length] = {'diff': distance, 'location': location};
									location.attr({'use':'use'});
								}
							}
						});
						locations = locations.sort(function(a,b){ return a.diff - b.diff; });
						var parent = wt.maps.locations.parent();
						var unusedLocations = parent.find('.location:not([use])');
						parent.empty();
						$.each(locations, function() {
							parent.append(this.location);
						});
						$.each(unusedLocations, function() {
							parent.append($(this));
						});
						wt.maps.addLocations(point);
					} else {
						alert('Sorry, that ZIP code could not be found');
					}
				}
			);
			wt.maps.map.checkResize();
		});
	}

})();