﻿var Search = Class.create();
Search.prototype = {
	initialize: function() {
		this.categories = $$('select.search-categories');
		this.subcategories = $$('select.search-subcategories');
		this.findCategories();
	},

	findCategories: function() {
		if (this.categories.length > 0) {
			this.categories = this.categories[0];
			this.subcategories = this.subcategories[0];
			this.subcategories.hide();
			Event.observe(this.categories, 'change', this.onCategoryChange.bind(this));
		}

		if (this.subcategories.length > 1) {
			this.subcategories.show();
		}
	},

	onCategoryChange: function() {
		var url = URL.parse(location.href);
		var query = url.queryKey;
		try {
			this.categories.up(1).addClassName('loading');
			/* Call the partial page */

			var url = url.file + "?";
			var hasCategory = false;

			for (var name in query) {
				if (query[name]) {
					if (name == "subcategory" || name == "partial") {
						continue;
					}

					url += name + "=";

					switch (name) {
						case "category":
							url += $F(this.categories);
							hasCategory = true;
							break;
						default:
							url += query[name];
							break;
					};

					url += "&";
				}
			}

			if (!hasCategory) {
				url += "category=" + $F(this.categories);
			}

			var updater = new Ajax.Replacer(this.subcategories, url + '&partial=1', { method: 'get', onComplete: this.onGetCategoriesComplete.bind(this), onFailure: this.onGetCategoriesFailure.bind(this) });
		}
		catch (e) { alert(e); }
	},

	onGetCategoriesComplete: function() {
		global.removeLoadingClass();
		this.subcategories = $$('select.search-subcategories')[0];
		(this.subcategories.options.length > 1) ? this.subcategories.show() : this.subcategories.hide();
	},

	onGetCategoriesFailure: function() {
		global.removeLoadingClass();
		this.subcategories.hide();
		alert('Failed to load categories. Please try again.');
	}
};

var search;
FastInit.addOnLoad(function() {
	search = new Search();
});
