var Local = {

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

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

};



if (!window['wt']) {
    window['wt'] = {};
    var wt = window['wt'];
    
    
    
}

(function() { // This is where jQuery code can safely go without foobarring prototype
	var $ = jQuery;
// These functions get called on DOM ready

	$(document).ready(function() {
		lightbox();
		
		$('a').click(function() { $(this).blur(); }); // prevents outlines on links for IE
		
		$('li.nav-guide').append($('div.drop').remove())
		$('li.nav-guide').hover(function(event){
			$('div.drop').show()
		}, function(event){
			$('div.drop').hide()
		
	 	});
	
	function lightbox() {
		var links = $('a[rel^=lightbox]');
		var overlay = $(jQuery('<div id="overlay" style="display: none"></div>'));
		var container = $(jQuery('<div id="lightbox" style="display: none"></div>'));
		var target = $(jQuery('<div class="target"></div>'));
		var close = $(jQuery('<a href="#close" class="close"><span>&times;</span> CLOSE</a>'));
		var loadingIcon = $(jQuery('<div class="loadingIcon">Loading</div>'));
	
		$('body').append(overlay).append(container);
		container.append(close).append(target);
		container.show().css({'top': Math.round(($(window).height() - container.outerHeight()) / 6) + 'px', 'left': Math.round(($(window).width() - container.outerWidth()) / 2) + 'px', 'margin-top': 0, 'margin-left': 0}).hide();
		
		
		close.click(function(c) {
			c.preventDefault();
			overlay.add(container).fadeOut('normal');
			loadingIcon.remove();

		});
		
		links.each(function(index) {
			var link = $(this);
			link.click(function(c) {
				c.preventDefault();
				container.addClass('loading');
				if(!container.is(':visible')) {
						target.children().remove();
						overlay.add(container).fadeIn("normal");
						$('div.guide_link').append(loadingIcon);

				} else {
					target.children().fadeOut("fast");

				}
				target.load(link.attr('href')+' .grabme');
				links.filter('.selected').removeClass('selected');
				link.addClass('selected');

			});
			link.attr({'lb-position': index});

		});
		
 	} // End Lightbox		
		
	$(window).load(function() {
		wt.maps() });
	
	$(window).unload(function() {
		GUnload() });
		
		
		wt.maps= function() {
			if(!$('#map').size()) {
				return;
				}
		
		$.browser.msie6 = jQuery.browser.msie &&
			    parseInt(jQuery.browser.version) == 6 &&
			    !window["XMLHttpRequest"];
		
		if($.browser.msie6) {
			alert('You must upgrade your browser to use TasteBuds interactive map')
		}
		
			wt.maps.init() };
		
	
		wt.maps.init = function() {
			var map = new GMap2(document.getElementById('map'));
			var Chattanooga = new GLatLng(35.054924,-85.313446);
			map.setCenter(Chattanooga, 12);
			map.setMapType(G_PHYSICAL_MAP);
			map.setUIToDefault();
			var locations = [];

			$('<div id="mapMessage"><span>Loading</span><p>Choose a category on the right to view providers below. Click a provider to see their position on the map. You may need to zoom out to view some providers.</p></div>').hide().appendTo('#map').fadeIn("slow");
			
			var mapUnits;
			var catLoad = {};
			var counter = 0;
			var categoryCount = 0;
			var markers = {};
			var timeOut = 15;
			
			
			function parseJS () {
				for(cat in units){
					var categories = units[cat];
					parseCategory(cat)
				}
				
			}
			
			function constructProvider(pro, con, cat_name) {
				var name = pro["name"] || '';
				var address = pro.address || '';
				var addressLine1 = pro.addressLine1 || '';
				var addressLine2 = pro.addressLine2 || '';
				var phone = pro.phone || '';
				var website = pro.website || '';
				var hours = pro.hours || '';
				var foods = pro.foods || '';
				
				if(name){
					jQuery("<div class='unit'><div class='name'><div class='mapThis'>Map This </div><ul><li><strong>"+name+"</strong></li><li class='smallprint'>"+foods+"</li><li class='smallprint'>"+hours+"</li></ul></div><ul class='address'><li>"+addressLine1+"</li><li>"+addressLine2+"</li></ul><ul class='contact'><li>"+phone+"</li><li>"+website+"</li></ul></div>").appendTo(con);
					markers[cat_name].push(pro);
				}
				$('div.ProviderInfo div.container').css('display','none');
				
				
			}
			
			function parseCategory (cat_name) { // The Loop that populates everything
				var category = units[cat_name]
				if(category){
					jQuery("<li class='"+cat_name+"' id='category-"+cat_name+"'>"+category.a+"</li>").appendTo("#providers ul");
					markers[cat_name] = []
				}
				
				catLoad[category] = false;
				
				var container = jQuery('<div class="container" id="container-'+cat_name+'"><h3>'+category.a+'</h3></div>').appendTo('.ProviderInfo')
				for(pro in category){
			    	var provider = category[pro];
					if(provider){
						constructProvider(provider, container, cat_name);
					}
				}
			}
					
			parseJS();
			
			makeMarkers();
			
			function makeMarkers(){
				for (cat in markers)
				{
					makeMarker(0, cat)
				}
			}

			function makeMarker(i, cat_name){
				if (i < markers[cat_name].length){
					var provider = markers[cat_name][i];
					var address = provider.address;
					var geo = new GClientGeocoder();
					console.log(provider.name);
					geo.getLocations(address, function(result){
						if(result.Status.code == 620){
							timeOut += 500;
							setTimeout(function(){makeMarker(i, cat_name)}, timeOut);
						} else if (result.Status.code == 200){
							timeOut = 15;
							if(result.Placemark){
								geocode = result.Placemark[0].Point.coordinates;
								addMarker(geocode, i, cat_name);
								setTimeout(function(){makeMarker(i+1, cat_name)}, timeOut);
							}
						} else {
							setTimeout(function(){makeMarker(i+1, cat_name)}, timeOut);
						}
						
					})
					
					

					function addMarker(geocode, i, cat_name){
						var point = new GLatLng(geocode[1], geocode[0])
						console.log('point = '+point)
						var marker = new GMarker(point)
						map.addOverlay(marker);
						marker.hide();
						
						var provider = markers[cat_name][i];
						provider['marker']=marker;
						var dis = markers[cat_name][i];
						
						var mapThisLink = "<li><span><a href=\"http://maps.google.com/maps?f=h&l=en&daddr="+reformatAddress(dis.name+', '+dis.addressLine1+', '+dis.addressLine2)+"&z=14\">Get Directions</a></span></li>";
						
						function reformatAddress(address) {
							return address.replace(/(\s)/gm,"+");
						}
						
						var blurb = $("<ul><li><b>"+dis.name+"</b></li><li>"+dis.addressLine1+"</li><li>"+dis.addressLine2+"</li><li>"+dis.phone+"</li><li>"+dis.website+"</a></li>"+mapThisLink+"</ul>").html();

						
						GEvent.addListener(marker, "click", function(){
							map.openInfoWindowHtml(point, blurb);
							map.panTo(point);
						})
						

						
						$($('#container-'+cat_name+' .unit div.mapThis').get(i)).click(function(){
							var center = provider.marker.getLatLng();
							map.openInfoWindowHtml(point, blurb);
							map.panTo(center);
							$('html, body').animate({scrollTop:0}, "fast");
						})
						
					}
				}
			
				else {
					catLoad[cat_name] = true;
					var finished = true;
					for (cat in units) {
						if (!catLoad[cat]) {
							finished = false;
							break;
						}
					}
					if (finished) {
						$('div#mapMessage').fadeOut("slow");
						
						$('#providers ul li').each(function(){
							$(this).click(function(){
								if ($(this).hasClass('activeCat'))
								{
									$(this).removeClass('activeCat')
								} 
								else 
								{
									$(this).addClass('activeCat');
								}
								var c = $(this).attr("id").replace('category-','');
								var con = 'div#container-'+c;
								toggleMarkers(c);
								if ($(con).is(":hidden")) {
									$(con).show();
								} else {
									$(con).hide();
								}
								map.closeInfoWindow();
							});
						});
						
						}
					return true;
				}
			}
			
			

			
			function toggleMarkers(cat_name){
				var providers = markers[cat_name];
				for (i=0; i<providers.length; i++) {
					var togglee = providers[i]["marker"];
					if(togglee) {
						console.log(cat_name);
						if (togglee.isHidden()){
							togglee.show();
						} else {
							togglee.hide();
						}
					}
				}
			}
			
			$('div#mapMessage').click(function () {
				$(this).fadeOut("slow");
			})
			


			


			} // end init
		
		
		
		
		
		wt.hero(); // Crossfades hero shots if applicable
	})
	
	$(window).load(function() { // These functions get called when everything has loaded
		
	})
	
	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(!$('.heroshots').size()) {
			return;
		}
		$('.heroshots').each(function(index) {
            var heroshot = $(this);
            var interval = null;
    		var fade = heroshot.find('input[name=fadevalue]');
    		fade = fade.val() * 1000;
    		heroshot.find('input[name=fadevalue]').remove();

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

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

		


		wt.hero.rotate = function(dir, heroshot) {
			if(typeof dir == 'undefined') {
				var dir = 'next'
			}
			if(typeof heroshot == 'undefined') {
				return
			}
			
			var images = heroshot.children('a,img')
			var current = heroshot.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])
				}
			}
            
            var fade = heroshot.attr('fade')
			current.removeAttr('current').fadeOut(fade)
			
			if(wt.hero.useCaptions) {
				heroshot.find('.holder').fadeOut(fade / 2, function(){
					heroshot.find('.holder').text(to.find('img').size() ? to.find('img').attr('alt') : to.attr('alt'))
					heroshot.find('.holder').fadeIn(fade / 2)
				})
			}

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

	// Heroshot options
	wt.hero.useForeground = true
	wt.hero.useControls = true
	wt.hero.useCaptions = true

})();