/**
 * Brownbear
 *
 * The parent object literal that we'll use as our Brownbear.
 * All direct children must be declared here.
 */
var Brownbear = {
	Controller: null,
	System: null,
	Home: null,
	Store: null
};

/**
 * Brownbear.Controller
 *
 * Run every page through here and feed it only the JS it needs.
 */
Brownbear.Controller = {
	init: function() {
		Brownbear.System.init();

		// Fire off JS based on URI segment
		var uri = document.location.pathname.split('/');
		
		if (uri[1] === '') { Brownbear.Home.init(); }

		if (uri[1] == 'store') { Brownbear.Store.init(); }
		
		if (uri[1] == 'washes-pricing' && uri[2] == 'tunnel') {  $('label[for="region"]').text("Pricing"); }

		if (uri[1] == 'store' && uri[2] == 'cart') { Brownbear.Store.initCart(); }

		if (uri[1] == 'store' && uri[2] == 'checkout') { Brownbear.Store.initCheckout(); }

		if (uri[1] == 'locations') { Brownbear.Locations.init(); }
	}
};

/**
 * Brownbear.System
 *
 * This is for global JS stuff. That is, items that get used
 * throughout the site (or at least on more than one page.
 */
Brownbear.System = {
	init: function() {
		// Always fire SY.System
		Ctm.System.init();

		
		//nav stuff		
		var navString = '<ul>' + 
		'<li><a href="/washes-pricing/tunnel/pricing-1">Seattle/Eastside</a></li>' +
		'<li><a href="/washes-pricing/tunnel/pricing-2">Snohomish County</a></li>' +
		'<li><a href="/washes-pricing/tunnel/pricing-2">South King County</a></li>' +
		'<li><a href="/washes-pricing/tunnel/pricing-2">Pierce County</a></li>' +
		'</ul>';
		$('#mainNav .tunnel').append(navString);
		
		$('#mainNav li ul').each(function() {
			$(this).siblings('a').addClass('dropDown');
		});
		
		// Fix orphans in heading tags in the main column
		$('#main h1, #main h2, #main h3').each(function() {
			var text = $(this).text();
			var html = $(this).html();
			var words = $(this).text().split(' ');
			var length = words.length;
			if(length >= 3) {
				words[length - 2] += '&nbsp;' + words[length - 1];
				words.pop();
				html = html.replace(text, words.join(' '));
				$(this).html(html);
			}
		});
	}
};

/**
 * Brownbear.Home
 *
 * Homepage JS (create more these for additional pages)
 */
Brownbear.Home = {
	init: function() {
		objElements.$html.addClass('homepage');
		Brownbear.Home.slideshow();
		Brownbear.Home.overflowSwitch();
	},

	slideshow: function() {
		$('#slider').slides({
			preload: true,
			play: 5000,
			pause: 2500,
			hoverPause: true,
			generatePagination: false,
			generateNextPrev: true,
			prev: 'home-prev',
			next: 'home-next'
		});
		
		$(window).resize($.debounce(200, Brownbear.Home.overflowSwitch));
	},
	
	overflowSwitch: function() {
		if ($(window).width() < 960) {
			$('html').css('overflowX', 'scroll');
		} else {
			$('html').css('overflowX', 'hidden');
		}
	}
};

/**
 * Brownbear
 *
 * Store JS
 */
Brownbear.Store = {
	options: {
		urls: {
			updateCart: '/store/api/update',
			getItems: '/store/api/getitems',
			checkout: '/store/api/checkout'
		}
	},
	totalItems: 0,

	init: function () {
		Brownbear.Store.getItems();
		Brownbear.Store.hijackAdd();
	},

	initCart: function() {
		Brownbear.Store.hijackRemove();
		Brownbear.Store.hijackUpdate();
		Brownbear.Store.viewCart();
	},

	// Add the Checkout button
	checkoutButton: function() {
		$('#checkoutbutton').remove();
		if(Brownbear.Store.totalItems > 0) {
			$('#cartdiv').after('<a href="/store/checkout"><div id="checkoutbutton"></div></a>');
		}
	},

	// Initialize the checkout page
	initCheckout: function () {
		Brownbear.Store.hijackCheckout();
		Brownbear.Store.toggleShipping();

		$('#shippingSame').change(function() {
			Brownbear.Store.toggleShipping();
		});

		// Add an empty div to display error messages later
		if($('.errors').length) {
			$('.errors').empty();
		} else {
			$('#checkout-form').prepend('<div class="errors"></div>');
		}
	},
	
	// Returns cart items
	getItems: function() {
		$.ajax({
			url: Brownbear.Store.options.urls.getItems,

			success: function(data) {
				if (data.status == 'ok') {
					Brownbear.Store.updateTotalItems(data.data.count);
				}
			}
		});
	},

	// Renders the shopping cart
	// Clears any extra rows before rendering
	viewCart: function () {
		$.ajax({
			url: Brownbear.Store.options.urls.getItems,

			success: function(data) {
				if (data.status == 'ok') {
					var cart = data.data;
					var html = Brownbear.Store.renderCart(cart.items);
					$('#cart-items').html(html);
					Brownbear.Store.updateSubtotal(cart.subtotal);
				}
			}
		});
	},

	// Returns the HTML for the cart
	renderCart: function(data) {
		var html = '';
		$.each(data, function(i, item) {
			html +=
				'<tr data-productid="' + item.productID + '">' +
					'<td width="100"><img src="/assets/uploads/' + item.image + '" /></td>' +
					'<td>' +
						'<strong>' + item.title + '</strong><br>' +
						item.description +
					'</td>' +
					'<td>';
			if(item.originalPrice !== undefined) {
				html += '<span class="original price">$' + item.originalPrice + '</span>' +
				'<span class="sale price">$' + item.price + '</span>';
			} else {
				html += '<span class="price">$' + item.price + '</span>';				
			}
			html += '</td>' +
					'<td><input type="number" min="0" value="' + item.quantity + '" class="quantity short" /></td>' +
					'<td class="delete-cell"><a href="#delete" class="remove-product">Delete</a></td>' +
				'</tr>';
		});

		if (html === '') {
			html += '<strong>Your cart is empty.</strong>';
			$('#update-cart').remove();
		}
		
		return html;
	},

	// Add a product to the cart
	hijackAdd: function() {
		$('.add-product').live('click', function(e) {
			e.preventDefault();

			$.ajax({
				url: Brownbear.Store.options.urls.updateCart,
				data: {
					products: { 0: {
						productID: $(this).attr('data-productid'),
						quantity: $('#product-' + $(this).attr('data-productid')).val(),
						increment: 1
					}}
				},

				success: function(data) {
					if (data.status == 'ok') {
						Brownbear.Store.updateTotalItems(data.data.count);

						// Sticky Notification
						$.sticky('An item was added to <a href="/store/cart">your cart</a>');
					}
				},

				error: function() {
					alert('Form submission error');
				}
			});
		});
	},

	// Remove a product from the cart
	hijackRemove: function() {
		$('.remove-product').live('click', function(e) {
			e.preventDefault();
			$productRow = $(this).parent().parent();
			$.ajax({
				url: Brownbear.Store.options.urls.updateCart,
				data : {
					products: { 0: {
						productID: $productRow.attr('data-productid'),
						quantity: 0
					}}
				},

				success: function(data) {
					if (data.status == 'ok') {
						$productRow.remove();
						Brownbear.Store.updateSubtotal(data.data.subtotal);
						Brownbear.Store.updateTotalItems(data.data.count);

						// Sticky Notification
						$.sticky('An item was removed from <a href="/store/cart">your cart</a>');
					}
				},

				error: function() {
					alert('Form submission error');
				}
			});
		});
	},

	// Update cart quantities
	hijackUpdate: function() {
		$('#update-cart').click(function(e) {
			e.preventDefault();

			// Build array of products and quantities
			var products = [];
			$('#cart-items input.quantity').each(function() {
				products.push({
					productID: $(this).parent().parent().attr('data-productid'),
					quantity: $(this).val()
				});
			});

			$.ajax({
				url: Brownbear.Store.options.urls.updateCart,
				data : {products: products},

				success: function(data) {
					if (data.status == 'ok') {
						Brownbear.Store.updateSubtotal(data.data.subtotal);
						Brownbear.Store.updateTotalItems(data.data.count);
						Brownbear.Store.viewCart();

						// Sticky Notification
						$.sticky('Quantities have been updated');
					}
				},
				error: function() {
					alert('Form submission error');
				}
			});
		});
	},

	// Hijack form submission
	hijackCheckout: function() {
		var $form = $('#checkout-form');

		$form.submit(function(e) {
			e.preventDefault();

			$.ajax({
				url: Brownbear.Store.options.urls.checkout,
				data : $form.serialize(),
				
				// Fade out the form, change cursor to waiting
				beforeSend: function() {
					$form.css('opacity', 0.5).css('cursor', 'progress');

					// Remove any previously invalid classes
					$('.invalid').removeClass('invalid');
				},

				success: function(data) {
					// Remove waiting styles
					$form.css('opacity', '').css('cursor', '');

					if (data.status == 'ok') {
						// Checkout succesful, redirect to confirmation page
						window.location = '/store/checkout/complete';
					} else {
						// Checkout failed. Add invalid class to elements with errors
						var errorMessages = '';
						$.each(data.data.errors, function(element, error) {
							errorMessages += '<div class="error">' + error + '</div>';
							$('[name="' + element + '"]').addClass('invalid');
						});

						// Show error messages at above the form
						$('.errors').html(errorMessages);

						// Move cursor to firt invalid element
						$('.invalid:first').focus();
					}
				},

				error: function() {
					$form.css('opacity', '').css('cursor', '');
					alert('There was an error in the checkout process');
				}
			});
		});
	},

	// Updates the total items in the cart summary
	updateTotalItems: function(total) {
		Brownbear.Store.totalItems = total;
		$('#total-items').html(total + ' items');

		// Add checkout button
		Brownbear.Store.checkoutButton();
	},

	// Updates the subtotal in the cart view
	updateSubtotal: function(subtotal) {
		$('#subtotal span').html('$' + subtotal.toFixed(2) );
	},

	// Toggles the shipping address fields
	toggleShipping: function() {
		if ($('#shippingSame').is(':checked')) {
			$('#shipping').hide();
			$('#shipping input:not(#shippingName), #shipping select').attr('disabled', 'disabled').removeAttr('required').parent().removeClass('required');
		} else {
			$('#shipping input:not(#shippingName), #shipping select').removeAttr('disabled').attr('required', 'required').parent().addClass('required');
			$('#shipping').show();
		}
	}
};

/**
 * Locations Map / Search
 */
Brownbear.Locations = {
	map: {},
	geocoder: {},
	center: {},
	infowindow: {},
	sidebar: $('#search-results'),
	options: {
		urls: {
			search: '/locations/search',
			googleMaps: '//maps.googleapis.com/maps/api/js?v=3.5&sensor=false&callback=Brownbear.Locations.initMap'
		}
	},

	init: function() {
		// Load Google Maps API
		$.getScript(Brownbear.Locations.options.urls.googleMaps);
	},

	// Initialize the Google Map
	initMap: function() {
		// Set default centered position
		Brownbear.Locations.center = new google.maps.LatLng(47.5, -122.5);
		Brownbear.Locations.geocoder = new google.maps.Geocoder();
		
		Brownbear.Locations.map = new google.maps.Map(
			document.getElementById('map'), {
				zoom: 8,
				center: Brownbear.Locations.center,
				mapTypeId: google.maps.MapTypeId.ROADMAP
			}
		);

		Brownbear.Locations.geocoder.geocode({'address': $('#locationSearch').val()}, function(results, status) {
			if (status != google.maps.GeocoderStatus.OK) {
				$('#error').html('No locations were found with the address provided.');
			} else {
				
				Brownbear.Locations.getLocations(results[0].geometry.location);
			}
		});

	},

	// API request for locations
	getLocations: function(location) {
		$.ajax({
			url: Brownbear.Locations.options.urls.search,
			data : {
				lat: 	location.Na, 
				lon: 	location.Oa,
				radius: $('#radius').val()
			},
			
			beforeSend: function() {},

			success: function(data) {
				if (data.data.locations.length > 0) {
					// There are results, add markers to map
					Brownbear.Locations.addMarkers(data.data.locations);
				} else {
					// No results, show error message
					Brownbear.Locations.sidebar.html('No results found.');
					Brownbear.Locations.map.setCenter(Brownbear.Locations.center);
				}
			},

			error: function() {
				alert('There was an error performing the search');
			}
		});
	},

	// Loops through all locations and adds markers to the map
	addMarkers: function(locations) {
		Brownbear.Locations.sidebar.empty();

		var bounds = new google.maps.LatLngBounds();
		
		// Create markers and sidebar items for each result
		$.each(locations, function(i, location) {

			// Add Google Maps link
			location.directions = '<a href="http://maps.google.com/maps?f=d&source=s_d&saddr=' + location.address + '+' + location.city + '+' + location.state + '+' + location.zip + '&hl=en" target="_blank">get directions</a>';
			
			// Add Pretty Address
			location.prettyAddress = location.address + '<br/>' + location.city + ', ' + location.state + ' ' + location.zip + '<br />';

			// Create a map point
			var point = new google.maps.LatLng(
				parseFloat(location.lat),
				parseFloat(location.lon)
			);
			bounds.extend(point);
			
			
			// Add marker to map, different icons depending on services available
			if (location.hours === '') {
				var marker = Brownbear.Locations.createMarker(point, location, '/assets/images/markerIcon2.png');
			} else {
				var marker = Brownbear.Locations.createMarker(point, location, '/assets/images/markerIcon.png');
			}
			
			
			// Add result to sidebar
			Brownbear.Locations.createSidebarEntry(location, marker);
		});

		// Create info window
		Brownbear.Locations.infowindow = new google.maps.InfoWindow({});

		// Re-center the map to show all the markers
		Brownbear.Locations.map.fitBounds(bounds);
	},

	// Returns one map marker
	createMarker: function(point, location, img) {
		var html = '<h4>' + location.title + '</h4>' + 
							location.prettyAddress +
							location.phone + '<br/>' + 
							location.directions;
		
		// Create marker
		var marker = new google.maps.Marker({
			position: 	point,
			map: 		Brownbear.Locations.map,
			icon: 		img,
			shadow: 	'/assets/images/markerShadow.png',
			zIndex:		1
		});

		// Add click listener
		google.maps.event.addListener(marker, 'click', function() {
			var infowindow = Brownbear.Locations.infowindow;
			if (infowindow) {
				infowindow.close();
			}
			infowindow.setContent(html);
			infowindow.open(Brownbear.Locations.map, marker);
		});

		return marker;
	},

	// Adds a location to the sidebar
	createSidebarEntry: function(location, marker) {
		// Round the distance down to one decimal
		var distance = parseFloat(location.distance).toFixed(1);

		// Google maps link

		// Build the markup
		var html = '<div class="location clearfix" id="location-' + location.locationID + '">';

		// Image / manager column
		html += '<div class="grid_5 alpha">';
		
		if (location.imageID && location.imageID !== 0 && location.image) {
			html += '<img src="/assets/uploads/' + location.image + '" class="locationimage"/>';
		} else {
			html += '<img src="/assets/uploads/nolocationimg.jpg" style="width:200px;" />';
		}
		
		html+= '<div class="clear"></div>';
		
		if (location.managerImageID && location.managerImageID !== 0 && location.managerImage) {
			html += '<img src="/assets/uploads/' + location.managerImage + '" class="managerimage"/>';
		}
		
		if (location.manager) {
			html += '<div class="manager">' + location.manager + '</div>';
		}
		
		html += '</div>';
		
		// Main Column
		html += '<div class="container_6">' +
			'<h2>' + location.title + ' #' + location.storeNumber + '</h2>' +
			'<div class="grid_3 alpha">' +
			'<h4>Distance from Search</h4>' +
			'<p>' + distance + ' miles</p>' +
			'<h4>Location</h4>' +
			'<p>' + location.address + '<br />' + location.city + ', ' + location.state + ' ' + location.zip + '</p>' +
			'<p>' + location.directions + '</p>';
			
		if (location.hours !== '') {
			html += '<h4>Hours</h4>' +
				'<p>' + location.hours + '</p>';
		}
		
		html +=	'<h4>Contact</h4>' +
			'<p>' + location.phone + '</p>' +
			'</div>';

		html += '<div class="grid_3 omega">';
		
		if (location.chevron == 'yes') {
			html += '<img src="/assets/images/chevron.png" />';
			html += '<h4>Chevron</h4><p>' + location.chevronHours + '</p>';
		}

		if (location.union76 == 'yes') {
			html += '<img src="/assets/images/76.png" />';
			html += '<h4>ConocoPhillips 76</h4><p>' + location.union76Hours + '</p>';
		}

		if (location.texaco == 'yes') {
			html += '<img src="/assets/images/texaco.png" />';
			html += '<h4>Texaco</h4><p>' + location.texacoHours + '</p>';
		}

		if (location.hungrybear == 'yes') {
			html += '<img src="/assets/images/bearmarketlogosmall.png" />';
			html += '<h4>Hungry Bear Market</h4><p>' + location.marketHours + '</p>';
		}
		
		html += '</div></div><div class="clear"></div>';

		// End div.location
		html += '</div>';
		
		// Append location markup to sidebar
		Brownbear.Locations.sidebar.append(html);

		// When you click on a result, it selects the appropriate map marker
		$('#location-' + location.locationID).live('click', function() {
			google.maps.event.trigger(marker, 'click');
			window.location = '#map-wrapper';
		});   
	}
};

/**
 * On Ready Event
 * Simple: Fire the appropriate init methods based on the url.
 * DO NOT STUFF JS CODE HERE. PUT IT WHERE IT BELONGS
 */
$(function() {
	Brownbear.Controller.init();
});

