var Snugabell = {
	Config: {
		
	},
	
	initialize: function() {
		$(function(){
			if ($('.content .tabs').size()) Snugabell.Tabs.initialize();
			if ($('.slideshow ul').size()) Snugabell.Slideshow.initialize();
			if ($('#sku-field').size()) Snugabell.Product.initialize();
			if ($('#retailers-map').size()) Snugabell.Retailers.initialize();
		});
	},
	
	Product: {
		initialize: function() {
			var p = Snugabell.Product;
			
			$('.option-field').change(function(){
				p.setSKU(p.generateSKU);
			});
			
			$('.buy-form').submit(function(){
				var valid = true;
				
				$('.option-field').each(function(){
					if ($(this).val() == '') valid = false;
				});
				
				return valid;
			});
		},
		
		setSKU: function(sku) {
			$('#sku-field').val(sku);
		},
		
		generateSKU: function() {
			var sku = [$("#product-sku").val()];
			$('.option-field :selected').each(function(){
				if ($(this).val()) sku.push($(this).val());
			});
			
			return sku.join("-");
		}
	},
	
	Slideshow: {
		initialize: function() {
			var s = Snugabell.Slideshow,
				c = Snugabell.Config,
				request = {};
			
			s.$element = $('.slideshow ul');
			if (s.$element.attr('data-slideshow')) request.slideshow = s.$element.attr('data-slideshow');
			if (s.$element.attr('data-id')) request.id = s.$element.attr('data-id');
			
			$.getJSON('/data/slideshow.json.php', request, function(data){
				$.each(data, s.addPhoto);
				s.$element.cycle({
					fx: 'fade',
					speed: 1000,
					timeout: 4000
				});
			});
			
			s.$element.fadeIn();
		},
		
		addPhoto: function(index, photo) {
			Snugabell.Slideshow.$element.append('<li><img src="'+photo.url+'" width="'+photo.width+'" height="'+photo.height+'" alt="" /></li>');
		},
		
		$element: null
	},
	
	Tabs: {
		initialize: function() {
			var tab;
			
			// Add event handlers
			$('.content .tabs a').click(function(){
				Snugabell.Tabs.setTab($(this).attr('href'));
			});
			
			if (tab = window.location.hash) Snugabell.Tabs.setTab(tab);
			if ("onhashchange" in window) {
				window.onhashchange = function(e) {
					console.log(e.newURL.match(/#.*$/));
					Snugabell.Tabs.setTab(e.newURL.match(/#.*$/));
					
				}
			}
		},
		
		setTab: function(tab) {
			$('.content .tabs a').removeClass('selected');
			$('.content .tabs a[href="'+tab+'"]').addClass('selected');
			
			$('.tabs-content').hide();
			$(tab+'-content').show();
		}
	},

	Retailers: {
		map: null,
		center: null,
		options: {},
		
		locations: {},
		
		country: null,
		province: null,
		city: null,
		
		template: '\
			<li id="location-<%= id %>">\
				<img src="/template/markers/<%= index %>.png" />\
				<% if (website) { %><a class="location" href="<%= website %>" target="_blank"><% } %>\
					<h3><%= name %></h3>\
					<p><%= address %>, <%= city %>, <%= stateprov %>, <%= zippost %></p>\
					<% if (website) { %><p><%= website %></p><% } %>\
				<% if (website) { %></a><% } %>\
				<div class="location-details">\
				</div>\
			</li>',
		
		onlineTemplate: '\
			<li id="location-<%= id %>">\
				<a class="location" href="<%= website %>" target="_blank">\
					<h3><%= name %></h3>\
					<p><%= website %></p>\
				</a>\
			</li>',
		
		initialize: function() {
			var r = Snugabell.Retailers;
			
			// Intiialize default options
			r.center = new google.maps.LatLng(0,0); // new google.maps.LatLng(60,-105);
			r.options = {
				zoom: 1, //3,
				center: r.center,
				mapTypeId: google.maps.MapTypeId.ROADMAP
			}
			
			// Initialize Google Map
			r.map = new google.maps.Map($('#retailers-map')[0], r.options);

			// Bind events
			$('#retailers-form').submit(function(){ return false; });
			$('#location-country-field').change(r.changeCountry);
			$('#location-stateprov-field').change(r.changeProvince);
			$('#location-city-field').change(r.changeCity);
			$('#location-search-button').click(r.searchLocation);
			$('#location-online-country-field').change(r.changeOnlineCountry);
			$('#location-reset-button').click(r.reset);
			
			// Compile template
			r.template = _.template(r.template);
			r.onlineTemplate = _.template(r.onlineTemplate);
			
			// Check for selected province & city
			r.country = $('#location-country-field option:selected').val();
			r.province = $('#location-stateprov-field option:selected').val();
			r.city = $('#location-city-field option:selected').val();
			if (r.city) $.getJSON('/data/locations.json.php', {country: r.country, stateprov: r.province, city: r.city}, r.loadLocations);		
		},
		
		changeCountry: function(e) {
			var r = Snugabell.Retailers;
			r.country = $('#location-country-field option:selected').val();
			
			if (r.country) {
				$.getJSON('/data/provinces.json.php', {country: r.country}, r.loadProvinces);

				$('#location-city-field').html('<option val="" selected="selected">&mdash;</option>');
				$('#location-city-field').attr('disabled', true);
			} else {
				$('#location-stateprov-field').html('<option val="" selected="selected">&mdash;</option>');
				$('#location-stateprov-field').attr('disabled', true);

				$('#location-city-field').html('<option val="" selected="selected">&mdash;</option>');
				$('#location-city-field').attr('disabled', true);
			}
		},
		
		changeProvince: function(e) {
			var r = Snugabell.Retailers;
			r.province = $('#location-stateprov-field option:selected').val();
			
			if (r.province) {
				$.getJSON('/data/cities.json.php', {country: r.country, stateprov: r.province}, r.loadCities);
			} else {
				$('#location-city-field').html('<option val="" selected="selected">&mdash;</option>');
				$('#location-stateprov-field').attr('disabled', true);
			}
		},
		
		changeCity: function(e) {
			var r = Snugabell.Retailers;
			r.city = $('#location-city-field option:selected').val();
			
			if (r.city) {
				$.getJSON('/data/retailers.json.php', {country: r.country, stateprov: r.province, city: r.city}, r.loadLocations);
			}
		},
		
		searchLocation: function(e) {
			var r = Snugabell.Retailers,
				location = $('#location-search-field').val(),
				within = $('#location-within-field option:selected').val();
			
			if (location && within) {
				$.getJSON('/data/retailers.json.php', {search: location, within: within}, r.loadLocations);
			} else {
				r.resetList();
				r.resetMap();
			}
		},
		
		changeOnlineCountry: function(e) {
			var r = Snugabell.Retailers,
				country = $('#location-online-country-field option:selected').val();
			
			if (country) {
				$.getJSON('/data/retailers.json.php', {online: true, country: country}, r.loadOnlineLocations);
			} else {
				r.resetList();
				$('#retailers-map').show();
			}
		},
		
		loadProvinces: function(data, textStatus, xhr) {
			var r = Snugabell.Retailers;
			
			if (data.length) {
				$('#location-stateprov-field').html('<option value="" selected="selected">Choose a region...</option>');
				
				$.each(data, function(index, province){
					$('#location-stateprov-field').append('<option>'+province+'</option>');
				});

				$('#location-stateprov-field').attr('disabled', false);

			} else {
				$('#location-stateprov-field').html('<option val="" selected="selected">&mdash;</option>');
				$('#location-stateprov-field').attr('disabled', true);
			}
		},
		
		loadCities: function(data, textStatus, xhr) {
			var r = Snugabell.Retailers;
			
			if (data.length) {
				$('#location-city-field').html('<option value="" selected="selected">Choose a city...</option>');
				
				$.each(data, function(index, city){
					$('#location-city-field').append('<option>'+city+'</option>');
				});

				$('#location-city-field').attr('disabled', false);

			} else {
				$('#location-city-field').html('<option val="" selected="selected">&mdash;</option>');
				$('#location-city-field').attr('disabled', true);
			}
		},
		
		loadLocations: function(data, textStatus, xhr) {			
			var r = Snugabell.Retailers,
				lat = 0.0,
				lng = 0.0;

			$('#retailers-map').show();
			google.maps.event.trigger(r.map, 'resize');

			if (data.length) {
				r.resetMap();
				r.resetList();
				
				$.each(data, function(index, data){
					var location = data;
					location.position = new google.maps.LatLng(location.lat, location.lng);
					location.marker = new google.maps.Marker({
						position: location.position,
						name: location.name,
						icon: '/template/markers/'+(index+1)+'.png',
						map: r.map
					});
					
					lat += parseFloat(location.lat);
					lng += parseFloat(location.lng);
					
					location.index = index+1;
					
					r.locations[index] = location;
					r.addLocation(location);
				});
				
				// Add event handlers
				$('.location').click(r.showLocation);
				
				// Set map to center of markers and zoom in			
				if (data.length > 1) {
					lat = lat / data.length;
					lng = lng / data.length;
					
					r.map.setCenter(new google.maps.LatLng(lat, lng));
					r.map.setZoom(11);
				} else {
					r.map.setCenter(new google.maps.LatLng(lat, lng));
					r.map.setZoom(14);
				}
			} else {
				r.resetList();
				r.resetMap();
			}
		},
		
		loadOnlineLocations: function(data, textStatus, xhr) {
			var r = Snugabell.Retailers;
			
			$('#retailers-map').hide();
			
			if (data.length) {
				r.resetList();
				
				$.each(data, function(index, data){
					r.addOnlineLocation(data);
				});
			} else {
				r.resetList();
			}
		},
		
		addLocation: function(location) {
			var html = Snugabell.Retailers.template(location);
			$('#retailers-list').append(html);
		},
		
		addOnlineLocation: function(location) {
			var html = Snugabell.Retailers.onlineTemplate(location);
			$('#retailers-list').append(html);
		},
		
		reset: function() {
			Snugabell.Retailers.resetList();
			Snugabell.Retailers.resetMap();
			
			$('#location-country-field').val('');
			
			$('#location-stateprov-field').html('<option val="" selected="selected">&mdash;</option>');
			$('#location-stateprov-field').attr('disabled', true);
			
			$('#location-city-field').html('<option val="" selected="selected">&mdash;</option>');
			$('#location-city-field').attr('disabled', true);
			
			$('#location-search-field').val('');
			
			$('#location-online-country-field').val('');
		},
		
		resetList: function() {
			$('#retailers-list').html('');
		},
		
		resetMap: function() {
			var r = Snugabell.Retailers;
			
			r.map.setCenter(r.center);
			r.map.setOptions(r.options);
			
			$.each(r.locations, function(index, location){
				location.marker.setMap(null);
			});
			
			r.locations = {};
		},
		
		showLocation: function(e) {
			e.preventDefault();
		}
	}
};
Snugabell.initialize();
