﻿var Products = Class.create();
Products.prototype = {
	initialize: function() {
		this.redirectFromBookmark();
		this.filterCategories();
	},

	redirectFromBookmark: function() {
		/* Check for anchor tags, and redirect to actual page.*/
		var url = URL.parse(location.href);

		if (url.anchor && url.anchor.indexOf(".aspx") != -1) {
			location.href = url.anchor;
		}
	},

	filterCategories: function() {
		/* Subcategory links first */
		if ($('header')) {
			var categories = $('header').select('div ul li a');

			/* Hookup the event handlers for each link */
			for (var x = 0, y = categories.length; x < y; x++) {
				var category = categories[x];
				Event.observe(category, 'click', this.onFilterCategory.bind(this));
			}
		}
	},


	/*******
	EVENT HANDLERS
	********/

	onFilterCategory: function(e) {
		var element = Event.element(e);
		var container = element.up(2);

		try {
			container.addClassName('loading');

			/* Call the partial page */
			var updater = new Ajax.Updater('content', element.href + '?partial=1', { method: 'get', onComplete: this.onFilterComplete.bind(this), onFailure: this.onFilterFailure.bind(this) });

			/* Google Analytics tracking */
			if (analytics) {
				analytics.trackPageView(element.href);
			}

			/* Set the location hash for bookmarking, etc */
			var url = URL.parse(element.href);
			location.hash = '#' + url.path;

			/* Stop the event */
			Event.stop(e);
		}
		catch (err) {
			location.href = element.href;
			global.removeLoadingClass();
		}
	},

	onFilterComplete: function(e) {
		this.filterCategories();
		//text.sifr();
		global.removeLoadingClass();

		/* Find the unknown HTML element <pagetitle> and replace the page title with its innerHTML */
		var content = $('content');
		var title = content.select('pagetitle');
		if (title && (title.length > 0)) {
			document.title = title[0].innerHTML;
			title[0].remove();
		}
		else {
			document.location = element.href;
		}
	},

	onFilterFailure: function(e) {
		global.removeLoadingClass();
		alert('Page load failed. Please try again.');
	}
};

var products;
FastInit.addOnLoad(function() {
	products = new Products(); 
});
