$(function () {
		
	function Select (id) {
		var el = document.getElementById(id),
			onChange = function () {},
			self = {
				getNode: function () {
					return el;
				},
				addItem: function (label, value) {
					$(el).append(prolific.Option(label, value));
					return this;
				},
				addBatch: function (batch) {
					var i,
						item;
					batch = batch.sort();
					for (i = 0; i < batch.length; i++) {
						item = batch[i];
						if (typeof item === 'string') {
							self.addItem(item, item);
						} else if (typeof item === 'object') {
							self.addItem(item.label, item.value);
						}
					}
					$(el).val(-1);
					return this;
				},
				getValue: function () {
					return $('option:selected', el).val();
				},
				onChange: function (func) {
					if (typeof func === 'function') {
						onChange = func;
					}
				},
				clear: function () {
					$(el).empty();
					return this;
				}
			};
		
		$(el).bind('change', function () {
			if (self.getValue == -1) {
				return false;
			}
			onChange.call(self, self.getValue());
		});
		
		return self;
	}
	
	function ChangeCallback (data, returnType) {
		return function (value) {
			if (returnType === 'serial') {
				$('h3.results_head').fadeTo(200, 1);
			} else {
				$('h3.results_head').fadeTo(200, 0);
			}
			$.getJSON('ajax/catalog.php', data, function (response) {
				if (typeof response === 'object') {
					prolific.liveFilter[returnType].clear().addItem('Select your ' + returnType + '...','-1').addBatch(response.data, response.prices || null, response.details || null, response.shipping);
					$('#liveFilter_' + returnType).parent().css('display', 'block');
				}
			});
		};
	}
	
	function displayResults (response) {
		prolific.liveFilter.results.populate(response.data);
	}
		
	prolific.extend('liveFilter', function () {
		return {};
	});
	
	prolific.liveFilter.extend('year', function () {
		var self = Select('liveFilter_year');
		self.onChange(function () {
			$('#liveFilter_model').parent().css('display','none');
			$('#liveFilter_cylinders').parent().css('display','none');
			$('#liveFilter_engine').parent().css('display','none');
			$('#results').empty();
			ChangeCallback({
				returnType: 'make',
				year: self.getValue()
			}, 'make')()
		});
		return self;
	});
	
	prolific.liveFilter.extend('make', function () {
		var self = Select('liveFilter_make');
		self.onChange(function () {
			$('#liveFilter_cylinders').parent().css('display','none');
			$('#liveFilter_engine').parent().css('display','none');
			$('#results').empty();
			ChangeCallback({
				returnType: 'model',
				year: prolific.liveFilter.year.getValue(),
				make: self.getValue()
			}, 'model')()
		});
		return self;
	});
	
	prolific.liveFilter.extend('model', function () {
		var self = Select('liveFilter_model');
		self.onChange(function () {
			$('#liveFilter_engine').parent().css('display','none');
			ChangeCallback({
				returnType: 'cylinders',
				year: prolific.liveFilter.year.getValue(),
				make: prolific.liveFilter.make.getValue(),
				model: self.getValue()
			}, 'cylinders')()
		});
		return self;
	});
	
	prolific.liveFilter.extend('cylinders', function () {
		var self = Select('liveFilter_cylinders');
		self.onChange(function () {
			ChangeCallback({
				returnType: 'engine',
				year: prolific.liveFilter.year.getValue(),
				make: prolific.liveFilter.make.getValue(),
				model: prolific.liveFilter.model.getValue(),
				cylinders: self.getValue()
			}, 'engine')()
		});
		return self;
	});
	
	prolific.liveFilter.extend('engine', function () {
		var self = Select('liveFilter_engine');
		self.onChange(function () {
			ChangeCallback({
				returnType: 'serial',
				year: prolific.liveFilter.year.getValue(),
				make: prolific.liveFilter.make.getValue(),
				model: prolific.liveFilter.model.getValue(),
				cylinders: prolific.liveFilter.cylinders.getValue(),
				engine: self.getValue()
			}, 'results')();
			$('h3.results_head').fadeTo(200, 1);
		});
		return self;
	});
	
	prolific.liveFilter.extend('results', function () {
		var resultTemplate = $('#templates .result').clone(),
			results = $('#results').get();
		
		function cleanPrice (price) {
			var split = (price || 'Call for pricing').toString().split('.'),
				intPart = split[0],
				decPart = (split[1] || '00') + '';
			if (!price) return split[0];
			if (decPart.length < 2) decPart += '0';
			return intPart + '.' + decPart.slice(0,2);
		}
		
		function calcOversize (specs, id) {
			var cubSize = specs.length * specs.width * specs.height,
				dimWeight = Math.ceil(cubSize >= 5184? cubSize / 194: specs.weight);
			/*
			if (dimWeight >= 100) {
				return '$95.00';
			} else if (dimWeight >= 82) {
				return '$45.00';
			} else if (dimWeight >= 78) {
				return '$45.00';
			} else if (dimWeight >= 45) {
				return '$30.00';
			} else if (dimWeight >= 27) {
				return '$20.00';
			*/
			if (id == 9203 || id== 9187) {
				
			} else if (dimWeight >= 1) {
				return '$20.00';
			} else {
				return '$0.00';
			}
		}
		
		function correctPrice (orig, shipping, id) {
			if (id == 9203 || id == 9187) {
				return orig + 89;
			} else if (shipping.weight > 0) {
				return orig + 20;
			} else {
				return orig;
			}
		}
		
		return {
			clear: function () {
				$(results).empty();
				return this;
			},
			addItem: function (a, b) {
				return this;
			},
			addBatch: function (arr, prices, details, shipping) {
				shipping = shipping || [];
				var a,
					carName = '';
				var fields = 'year make model engine'.split(' '),
					f;
				for (f in fields) {
					carName += '<span class="' + fields[f] + '"> ' + prolific.liveFilter[fields[f]].getValue() + (fields[f] === 'engine'? 'L':'') + '</span> ';
				}
				this.clear();
				for (a = 0; a < arr.length; a++) {
					$('#results').append('<li class="result product"></li>');
					$('#results li:last')
						.append('<img class="thumb product-image" src="http://www.globalconverters.com/images/products/' + arr[a] + '.jpg" />')
						.append('<span class="serial">Catco Serial #' + arr[a] + '</span> ' + carName)
						.append('<p class="details"><strong>Notes:</strong> ' + prolific.defs.wrapEntities(details[a]).toLowerCase() + '</p>')
						.append('<div class="info"><span class="price">$' + cleanPrice(correctPrice(prices[a], shipping[a], arr[a])) + '</span><input value="#' + arr[a] + ' for the ' + $(carName).text() + '" class="product-title" type="hidden"><input value="' + cleanPrice(correctPrice(prices[a], shipping[a], arr[a])) + '" class="product-price" type="hidden"><div title="Add to cart" role="button" tabindex="0" class="googlecart-add-button"></div></div>');
						//.append('<input type="hidden" class="product-shipping" value="' + ((shipping[a]? shipping[a].weight: 0) > 0? '30.00':'0.00') + '"/>');
						//.append(shipping[a].weight > 0? '<input type="hidden" class="product-shipping" value="' + calcOversize(shipping[a], arr[a]) + '"/>': '<input type="hidden" class="product-shipping" value="$0.00"/>');
					if (!prices[a]) {
						$('#results li:last').hide();
					} else {
						$('#results li:last .acr').each(function (i) {
							$(this).tooltip($(this).attr('title')).removeAttr('title');
						});
					}
				}
			}
		};
	});
	
	
	//Set up ajax things
	var $meter = $('<img id="progress" src="/images/progress.gif" width="66" height="22" style="position: absolute; top: 50%; left: -9999px"/>').appendTo('body');
	$meter.ajaxStart(function () {
		$(this).css({
			left: '50%'
		});
	}).ajaxStop(function () {
		$(this).css({
			left: '-9999px'
		});
	});
});
