
var ProductFilter = new Class({
	
	initialShown: {},
	shown: {},
	reg: '',
	updateListeners: [],
	showing: 0,
	
	initialize: function(listID, filterID, shownToStart) {
		this.listID = listID;
		this.filterID = filterID;
		this.shown = Json.evaluate(shownToStart);
		this.initialShown = Json.evaluate(shownToStart);
		this.match($$('#' + this.filterID + ' input[name=q]')[0].value);
	},
	
	hide: function(type, specifier) {
		var myClass = type + '-' + specifier;
		this.shown = this.shown.remove(myClass);
		$('sel-' + myClass).removeClass('selected');
		this.filter();
	},
	
	show: function(type, specifier) {
		var myClass = type + '-' + specifier;
		this.shown.push(myClass);
		$('sel-' + myClass).addClass('selected');
		this.filter();
	},
	
	showOnly: function(type, specifier) {
		var myClass = type + '-' + specifier;
		$H(this.initialShown).each(function(classes, theType) {
			classes.each (function(theClass) {
				if (!this.shown[theType].contains(theClass)) {
					this.shown[theType].push(theClass);
					$('sel-' + theClass).addClass('selected');
				}
			}.bind(this));
		}.bind(this));
		this.initialShown[type].each(function(s) {
			// only matching within a type, so if brand we leave app alone and vice versa.
			if (s != myClass && this.shown[type].contains(s)) {
				this.shown[type] = this.shown[type].remove(s);
				$('sel-' + s).removeClass('selected');
			}
		}.bind(this));
		if (!this.shown[type].contains(myClass)) {
			this.shown[type].push(myClass);
			$('sel-' + myClass).addClass('selected');
		}
		this.filter();
	},
	
	toggleOnly: function(type, specifier) {
		var myClass = type + '-' + specifier;
		if (this.shown[type].length == 1 && this.shown[type].contains(myClass)) {
			this.initialShown[type].each(function(s) {
				// only matching within a type, so if brand we leave app alone and vice versa.
				if (!this.shown[type].contains(s)) {
					this.shown[type].push(s);
					$('sel-' + s).addClass('selected');
				}
			}.bind(this));
			this.filter();
		} else {
			this.showOnly(type, specifier);
		}
	},
	
	toggle: function(type, specifier) {
		var myClass = type + '-' + specifier;
		if (this.shown.contains(myClass)) {
			this.hide(type, specifier);
		} else {
			this.show(type, specifier);
		}
	},
	
	match: function(reg) {
		var r = reg.split(' ');
		this.reg = r.map(function(str) {
			return new RegExp(str, 'im');
		});
		this.filter();
	},
	
	filter: function() {
		//var r = new RegExp(this.reg, 'im');
		var totalShowing = 0;
		var totalHidden = 0;
		var lis = $$("#" + this.listID + ' li');
		lis.each(function(li) {
			// filter by text first.
			var show = true;
			var aToSearch = $(li.getElementsByTagName('a')[1]);
			var str = aToSearch.getText() + ' ' + aToSearch.title;
			this.reg.each(function(r){
				if (!r.test(str)) {
					show = false;
				}
			});
			
			$H(this.shown).each(function(classes, type) {
				if (show && (this.shown[type].length != this.initialShown[type].length)) {
					show = classes.filter(function (cn) {
						return li.hasClass(cn);
					});
					if (show.length) {
						show = true;
					} else {
						show = false;
					}
				}
			}.bind(this));
			
			if (show) {
				li.style.display = "block";
				totalShowing++;
			} else {
				li.style.display = "none";
				totalHidden++;
			}
		}.bind(this));
		var text = (totalHidden > 0) ? totalShowing + ' of ' + lis.length : totalShowing;
		$$("#" + this.filterID + ' h4 i.count')[0].setText('(' + text + ')');
		if ($defined($('productCount'))) {
			$('productCount').setText('(' + text + ')');
		}
		
		this.showing = totalShowing;
		
		//call the listeners
		this.updateListeners.each(function(arg) {
			arg.fn.call(arg.obj);
		});
	},
	
	addUpdateListener: function(obj, fn) {
		this.updateListeners.push({'obj': obj, 'fn': fn});
	}
	
});

var ProductFinder = new Class({
	initialize: function(wrapperID) {
		var pfTabs = new PodTabbed(wrapperID, 'apps,brands,mts', {callback: this.tabChange.bind(this)});
		this.wrapper = $(wrapperID);
		var brandTabID = 'tabbedContent_brands';
		var appTabID = 'tabbedContent_apps';
		var mtTabID = 'tabbedContent_mts';
		this.brandTab = $(brandTabID);
		this.appTab = $(appTabID);
		this.mtTab = $(mtTabID);
		this.brandLinks = $ES('a', brandTabID);
		this.appLinks = $ES('a', appTabID);
		this.mtLinks = $ES('a', mtTabID);
		//this.links = $ES('.pickList a', wrapperID);
		
		this.brandLinks.each(function(link) {
			var oldHref = link.href.replace(window.location.protocol + '//' + window.location.host + '/', '');
			link.href="javascript:productFinder.select('brand', '" + oldHref + "')";
		});
		
		this.appLinks.each(function(link) {
			var oldHref = link.href.replace(window.location.protocol + '//' + window.location.host + '/', '');
			link.href="javascript:productFinder.select('app', '" + oldHref + "')";
		});
		
		this.mtLinks.each(function(link) {
			var oldHref = link.href.replace(window.location.protocol + '//' + window.location.host + '/', '');
			link.href="javascript:productFinder.select('mt', '" + oldHref + "')";
		});
		
		this.statusBar = $E('.navbar', wrapperID);
		this.filterArea = $E('.filterWrapper', wrapperID);
		this.currentTab = 'apps';
		
	},
	
	select: function(type, url) {
		//console.log(type, url);
		var args = {
			'format': 'thumb',
			'type': type,
			'url': url
		};
		$('tabbedContent_' + type + 's').style.display = 'none';
		
		base_ajax('ProductFinderFilter', MODULES_URL + '/products/controllers/fn-product-list.php', Object.toQueryString(args), 'productFinder.ready("' + type + '", "' + url + '");');
	},
	
	ready: function(type, url) {
		showHide('ProductFinderFilter');
		
		//EVAL?!? Gross, yes, but it works.  Heaven help us all.
		// note that earlier I was trying to use mootools' getText, but apparently that doesn't work on a <script> in ie6.
		var script = $('setupFilter').innerHTML;
		eval(script);
	},
	
	tabChange: function(tabName) {
		this.currentTab = tabName;
		$('ProductFinderFilter').style.display = 'none';
	},
	
	clear: function() {
		$("tabbedContent_" + this.currentTab).style.display = 'block';
		this.tabChange(this.currentTab);
	}
	
});

var ProductComparables = new Class({
	productfilter: {},
	compareButtons: [],
	compareForm: {},

	initialize: function(productFilter) {
		this.productFilter = productFilter;
		this.productFilter.addUpdateListener(this, this.filterUpdated);
		this.compareForm = $('compareForm');
		this.filterUpdated();
	},
	
	filterUpdated: function() {
		this.compareButtons = $ES('div.compare', this.compareForm);
		if (this.productFilter.shown.mch.length == 1 && this.productFilter.showing > 1) {
			//we can allow the product compare boxes & buttons to show when there is only one product type showing, and there are enough items to create a comparison (that is, more than 1).
			this.compareButtons.each(function(e) {
				var cbox = $E('input', e);
				cbox.checked = false;
				e.style.display = 'block';
			});
		} else {
			this.compareButtons.each(function(e) {
				var cbox = $E('input', e);
				if (cbox) cbox.checked = false;
				if (e && e.style) e.style.display = 'none';
			});
		}
	},
	
	compare: function() {
		var qstr = this.compareForm.toQueryString();
		var qvars = qstr.split('&');
		var postVar = {};
		var prodIDs = [];
		qvars.each(function(qvar) {
			var q = qvar.split('=');
			if (q[0] == 'productIDs[]') {
				prodIDs.push(q[1]);
			} else {
				postVar[q[0]] == q[1];
			}
		});
		if (prodIDs.length > 1 && prodIDs.length < 7) {
			// form the request and redirect
			postVar['p'] = prodIDs.join('-');
			qstr = Object.toQueryString(postVar);
			window.location = this.compareForm.action + '?' + qstr;
		} else {
			//send error
			var warningBox = $E('h3 span.WARNING', $('ProductFinderFilter'));
			if (prodIDs.length <= 1) {
				warningBox.setText('You must select at least 2 items to compare.');
			} else {
				warningBox.setText('You cannot select more than 6 items to compare.');
			}
		}
	}
	
});

var QuickCompare = new Class({
	'initialize': function (compareFormID) {
		this.compareForm = $(compareFormID);
	},
	
	'compare': function() {
		var qstr = this.compareForm.toQueryString();
		var qvars = qstr.split('&');
		var postVar = {};
		var prodIDs = [];
		qvars.each(function(qvar) {
			var q = qvar.split('=');
			if (q[0] == 'productIDs[]') {
				prodIDs.push(q[1]);
			} else {
				postVar[q[0]] == q[1];
			}
		});
		// form the request and redirect
		postVar['p'] = prodIDs.join('-');
		qstr = Object.toQueryString(postVar);
		window.location = this.compareForm.action + '?' + qstr;
	}
});

