var Filter = Class.create();
Filter.prototype = {
	initialize: function(trigger, pulldown, target, options) {
		this.trigger  = $(trigger);
		this.pulldown = $(pulldown);
		this.target   = $(target);
		this.options  = Object.extend({
							eventCat: ''
							}, options || {});
		this.setup();
	},
	setup: function() {
		this.elements     = this.pulldown.getElementsBySelector('a');
		this.title        = this.trigger.getElementsBySelector('span').first();
		this.defaultTitle = this.title.innerHTML;
		//this.resize();
		
		Event.observe(this.trigger, 'click', this.show.bind(this));
		
		this.elements.each(function(el) {
			el.onclick = function() {
				this.select(el);
				return false;
			}.bind(this);
		}.bind(this));
	},
	show: function(event) {
		this.pulldown.show();
		this.listener = this.hide.bindAsEventListener(this);
		Event.observe(this.pulldown, 'click', this.listener);
		Event.observe(this.pulldown, 'mouseleave', this.listener);
		Event.stop(event);
	},
	hide: function(event) {
		this.pulldown.hide();
		Event.stopObserving(this.pulldown, 'click', this.listener);
		Event.stopObserving(this.pulldown, 'mouseleave', this.listener);
		Event.stop(event);
	},
	select: function(option) {
		var title   = '';
		
		var images = option.getElementsByTagName('img');
		if (images.length > 0) {
			title = images[0].alt;
		} else {
			title = option.innerHTML.replace(/\s*\([0-9]+\)$/, '')
		}
		
		switch(title) {
			case 'All':
			case 'ALL':
				this.selectedTitle   = 'All';
				this.title.innerHTML = this.defaultTitle;
				this.filter('ALL');
				break;
			default:
				this.selectedTitle   = title;
				this.title.innerHTML = title;
				this.filter(option.className);
				break;
		}
		
		if (this.options.eventCat) {
			var label = '';
			
			switch(this.trigger.getAttribute('id')) {
				case 'colorSelect':
					label += 'By Color';
					break;
				case 'collectionSelect':
					label += 'By Collection';
					break;
				case 'ecoShopSelect':
					label += 'Eco Choices';
					break;
				default:
					label += this.defaultTitle;
					break;
			}
			
			label += ' - ' + this.selectedTitle;
			GoogleAnalytics.trackEvent(this.options.eventCat, 'Filter', label)
		}
	},
	filter: function(category) {
		var colors = this.target.getElementsBySelector('li');
		for (var i = 0; i < colors.length; i++) {
			var color = colors[i];
			if (category == 'ALL' || color.hasClassName(category)) {
				color.show();
			} else {
				color.hide();
			}
		}
		
		//this.resize();
		
		(this.options.onChange || Prototype.emptyFunction)(this);
	},
	resize: function() {
		var triggerWidth = this.trigger.getWidth();
		if (triggerWidth < 110) {
			this.trigger.style.width = '110px';
		}
	},
	reset: function() {
		this.title.innerHTML = this.defaultTitle;
	}
}

/*--------------------------------------------------------------------------*/

var ColorBrowser = Class.create();
ColorBrowser.prototype = {
	initialize: function() {
		this.selColor = null;
		this.sortOpts = $('sort').getElementsBySelector('a');
		this.params = {
			sortOrder: 'SortProductField:productWidth',
			sortAscending: 'Y',
			clearSearch: 'Y'
		}
		
		this.pageName = '';
		if ($('colorScroller')) {
			this.pageName = 'Shop by Color';
		} else if ($('collectionScroller')) {
			this.pageName = 'Shop by Collection';
		}
		
		var theFilter = $('colorSelect') || $('collectionSelect');
		this.filter   = new Filter(theFilter, 'colorPulldown', 'colorSet', {
			eventCat: this.pageName, onChange: function() { this.scroller.reset() }.bind(this)
		});
		
		setTimeout(this.setup.bind(this), 500);
	},
	setup: function() {
		$('colorSets').style.width = $('colorSet').getWidth() + 2 + "px";
		this.colors   = $('colorSet').getElementsBySelector('a');
		this.scroller = new Control.Scroller('colorSets', 'knob', 'track', {
			axis:  'horizontal',
			up:    'scrollLeft',
			down:  'scrollRight',
			delta: 85
		});
		
		if ($('activeColor')) {
			this.scroller.moveTo('activeColor');
			this.selColor = $('activeColor').down('a');
		}
		
		var color_listener = this.selectColor.bindAsEventListener(this);
		this.colors.each(function(el) {
			Event.observe(el, 'click', color_listener); });
		
		var sort_listener = this.sortResults.bindAsEventListener(this);
		this.sortOpts.each(function(el) {
			if (el.hasClassName('active')) {
				this.selSortOpt = el;
			}
			Event.observe(el, 'click', sort_listener);
		}.bind(this));
	},
	selectColor: function(event) {
		this.selColor = Event.findElement(event, 'a');
		var colorEnvelopes = this.selColor.down('img').alt
		var colorName = colorEnvelopes.replace(/ Envelopes/,"");
		document.title = colorEnvelopes + ' - ActionEnvelope.com';
		if ($('instructions')) {
			$('instructions').innerHTML = '"' + colorName + '" is available in the sizes below.';
		}
		this.addCheckmark();
		this.getResults();
		GoogleAnalytics.trackEvent(this.pageName, 'Browse', colorName);
		Event.stop(event);
	},
	addCheckmark: function(el) {
		if ($('checkmark')) {
			var checkmark = $('checkmark');
			Element.removeClassName(checkmark.parentNode, 'active');
			Element.remove(checkmark);
		}
		Element.addClassName(this.selColor.parentNode, 'active');
		new Insertion.After(this.selColor, '<div id="checkmark" class="check"></div>');
	},
	getResults: function() {
		var params = Object.extend({}, this.params);
		if (this.selColor) {
			var category = this.selColor.href.match(/category_id=([^;]+)/);
			params.category_id = category[1];
			params.clearSearch = 'Y';
		}
		
		$('results').hide();
		$('progress').show();
		var myAjax = new Ajax.Updater('results', '/ae/control/loadColorResults',
			{ method: 'get', parameters: params, onComplete: function() {
				new Highlights('results');
				setTimeout(function() {
					$('progress').hide();
					$('results').show();
				}, 125);
			}});
	},
	sortResults: function(event) {
		this.selSortOpt.removeClassName('active');
		this.selSortOpt.removeClassName('asc');
		this.selSortOpt.removeClassName('desc');
		
		this.selSortOpt = Event.element(event);
		this.selSortOpt.addClassName('active');
		
		var sortby = this.selSortOpt.innerHTML.strip();
		switch(sortby) {
			case 'Item Name' : this.params.sortOrder = 'SortProductField:productName'; break;
			case 'Size' : this.params.sortOrder = 'SortProductField:productWidth'; break;
			case 'Price' : this.params.sortOrder = 'SortProductPrice:DEFAULT_PRICE'; break;
		}
		
		if (this.params.sortAscending == 'Y') {
			this.params.sortAscending = 'N';
			this.selSortOpt.addClassName('asc');
		} else {
			this.params.sortAscending = 'Y';
			this.selSortOpt.addClassName('desc');
		}
		this.getResults();
		Event.stop(event);
	}
}

/*--------------------------------------------------------------------------*/

var HomeFilter = Class.create();
Object.extend(Object.extend(HomeFilter.prototype, Filter.prototype), {
	filter: function(category) {
		var colors = this.target.getElementsBySelector('li');
		if (category == 'ALL') {
			category = this.options.type || '';
		}
		for (var i = 0; i < colors.length; i++) {
			var color = colors[i];
			if (color.hasClassName(category)) {
				color.show();
			} else {
				color.hide();
			}
		}
		
		this.resize();
		
		(this.options.onChange || Prototype.emptyFunction)(this);
	}
});

/*--------------------------------------------------------------------------*/

var HomeBrowser = Class.create();
HomeBrowser.prototype = {
	initialize: function() {
		this.container = $('browser');
		this.items     = $('colorSet').getElementsByTagName('li');
		this.color     =  {
			button: 'colorButton',
			loaded: true,
			filter: new HomeFilter('colorSelect', 'colorPulldown', 'colorSet',
						{type: 'COLORS', eventCat: 'Home Page', onChange: function() { this.scroller.reset() }.bind(this)})
		}
		this.collection = {
			button: 'collectionButton',
			loaded: false,
			filter: new HomeFilter('collectionSelect', 'collectionPulldown', 'colorSet',
						{type: 'COLLECTIONS', eventCat: 'Home Page', onChange: function() { this.scroller.reset() }.bind(this)})
		}
		this.setup();
	},
	setup: function(event) {
		Event.observe(this.color.button, 'click', this.showColors.bindAsEventListener(this));
		Event.observe(this.collection.button, 'click', this.showCollections.bindAsEventListener(this));
		
		this.scroller = new Control.Scroller('colorSets', 'knob', 'track', {
							axis:  'horizontal',
							up:    'scrollLeft',
							down:  'scrollRight',
							delta: 85
						});
		this.scroller.reset();
	},
	showColors: function(event) {
		var el = Event.findElement(event, 'a');
		if (el.hasClassName('active')) {
			this.hide(this.collection);
			this.show(this.color);
			this.swap(this.color.filter);
			GoogleAnalytics.trackEvent('Home Page', 'Tab', 'Shop by Color');
		}
		Event.stop(event);
	},
	showCollections: function(event) {
		var el = Event.findElement(event, 'a');
		if (el.hasClassName('active')) {
			this.hide(this.color);
			this.show(this.collection);
			if (this.collection.loaded == false) {
				this.loadCollections();
			} else {
				this.swap(this.collection.filter);
			}
			GoogleAnalytics.trackEvent('Home Page', 'Tab', 'Shop by Collection');
		}
		Event.stop(event);
	},
	loadCollections: function() {
		new Ajax.Request('/ae/control/loadColorScroller', {
			method:     'get',
			parameters: {'searchPage': 'shopByCollection'},
			onComplete: function(transport) {
				this.collection.loaded = true;
				var items = $('colorSet').getElementsByTagName('li');
				var total = items.length;
				for (var i = 0; i < total; i++) {
					Element.hide(items[i]);
				}
				new Insertion.Bottom('colorSet', transport.responseText);
				this.scroller.reset();
			}.bind(this)
		});
	},
	hide: function(obj) {
		$(obj.button).addClassName('active');
		obj.filter.trigger.hide();
	},
	show: function(obj) {
		$(obj.button).removeClassName('active');
		obj.filter.trigger.show();
	},
	swap: function(filter) {
		filter.filter('ALL');
		filter.reset();
		this.scroller.reset();
	}
}

/*--------------------------------------------------------------------------*/

Event.onDOMReady(function(){
	if ($('holidayShop') || $('recycleShop')) {
		$('colorSets').style.width = $('colorSet').getWidth() + 2 + "px";
		new Control.Scroller('colorSets', 'knob', 'track', {
			axis:  'horizontal',
			up:    'scrollLeft',
			down:  'scrollRight',
			delta: 85
		});
	} else if ($('homepage')) {
		new HomeBrowser();
	} else if ($('colorSets')){
		new ColorBrowser();
	} else if ($('collection')) {
		$$('a[href^=#]:not([href=#])').each(function(element) {
			element.observe('click', function(event) {
				new Effect.ScrollTo(this.hash.substr(1));
				Event.stop(event);
			}.bindAsEventListener(element))
		})
	}
});