(function() {
	// If the user arrives to a non-hashed URL, redirect to a hashed URL
	// Eg. http://www.stayfocused.fi/products/ed -> http://www.stayfocused.fi/products#!/ed
	var splitPath = location.pathname.substring(1).split('/');
	if (splitPath[0] == 'products' && splitPath.length >= 2) {
		window.location.href = '/products#!/'+splitPath[1];
		return;
	}
}());

$(window).bind('hashchange', function() {
	var splitPath = location.pathname.substring(1).split('/');
	var splitHash = location.hash.substring(3).split('/');
	
	// Load and display a product
	function showProduct(urlTitle, showDetails) {
		// Find the box inside which the content will be loaded.
		var productEl = $('#product-'+urlTitle);

		// Mark the box loading
		// See scripts.js for details about the edMarkLoading method
		if (!$('#product-'+urlTitle).edMarkLoading()) {
			return;
		}

		// Open the box
		productEl.edOpen();

		// Load the content in a container element
		var container = $('<div></div>');
		
		var contentUrl = '/products/'+urlTitle;
		
		if (showDetails == true) {
			contentUrl += '/details';
		}
		
		container.load(contentUrl+' #product-'+urlTitle+' .content', function() {
			// If a .content element was already present, remove it
			$('#product-'+urlTitle+' .inner .content').remove();
			
			// Place the loaded .content inside the box's .inner element
			var contentEl = container.find('.content');
			$('#product-'+urlTitle+' .inner').append(container.find('.content'));
			
			if (showDetails == true) {
				// Initialize tabs
				contentEl.find('.tab-group').edTabs();
			}

			FB.XFBML.parse();
			
			// Mark loading completed
			// See scripts.js for details about the edMarkLoadingCompleted method
			$('#product-'+urlTitle).edMarkLoadingCompleted();
		});
	}
	
	// Check if we are on the frontpage or the products page
	// and parse the hash appropriatelly
	if (splitPath[0] == 'frontpage' || splitPath[0] == '') {
		if (splitHash[0] == 'products') {
			showProduct(splitHash[1]);
		}
	} else if (splitPath[0] == 'products' && splitPath.length == 1) {
		if (splitHash[0] != '') {
			if (splitHash[1] == 'details') {
				showProduct(splitHash[0], true);
			} else {
				showProduct(splitHash[0]);
			}
		}
	}
});
