(function ()
{
	function panelHover (obj, content, options)
	{
		options.custom = options.custom || false;

		// IE 6 calculates coordinates incorrectly in position relative mode (2/20/2009 MCB)
		if (!options.custom)
		{
			if($.browser.msie && parseInt($.browser.version)<=6)
			{
				obj.style.position = 'absolute';
			}
			else
			{
				obj.style.position = 'relative';
			}
		}

		if (typeof options === 'undefined')
		{
			var options = {};
		}

		// pre-render options (MCB)
		if ((typeof options['soloFlag'] !== 'undefined') && (options['soloFlag'] === true))
		{
			$('.panelHover').remove();

			// get rid of select boxes in older versions of IE (1/21/2009 MCB)
			// as they do no obey z-index and are always on top (1/21/2009 MCB)
			if($.browser.msie && parseInt($.browser.version)<=6)
			{
				$('select').css('visibilty', 'visible');
			}
		}

		if ((typeof options['hideSelectsFlag'] !== 'undefined') && (options['hideSelectsFlag'] === true))
		{
			// get rid of select boxes in older versions of IE (1/21/2009 MCB)
			// as they do no obey z-index and are always on top (1/21/2009 MCB)
			if($.browser.msie && parseInt($.browser.version)<=6)
			{
				$('select').css('visibility', 'hidden');
			}
		}

		if ((!options['backgroundColor']) && (!options['cssClass']))
		{
			options['backgroundColor'] = 'white';
		}

		if (!options['borderColor'])
		{
			options['borderColor'] = '#999';
		}

		var tempDiv                   = document.createElement('DIV');
		if(options['backgroundColor'])
		{
			tempDiv.style.backgroundColor = options['backgroundColor'];
		}
//		tempDiv.style.width    = obj.offsetWidth + 'px';
		tempDiv.style.position        = 'absolute';
		tempDiv.style.left            = (options.custom ? 0 : obj.offsetLeft) + 'px';
		tempDiv.style.top             = (options.custom ? 0 : (obj.offsetTop + obj.offsetHeight)) + 'px';
		tempDiv.style.borderStyle     = 'solid';
		tempDiv.style.borderWidth     = '1px';
		tempDiv.style.borderColor     = options['borderColor'];
		tempDiv.style.padding         = '3px';
		tempDiv.style.zIndex          = '5';
		tempDiv.style.minWidth        = '90px';
		tempDiv.className             = 'panelHover' + ((typeof options['cssClass'] !== 'undefined')?(' ' + options['cssClass']):'');
		tempDiv.innerHTML             = content;
		obj.parentNode.insertBefore(tempDiv, obj.nextSibling);

		var me = this;

		if (options['closeType'] === 'text')
		{
			var tempP=document.createElement('P');
			tempP.innerHTML               = 'x Close';
			tempP.style.position          = 'absolute';
			tempP.style.color             = '#005288';
			tempP.style.fontWeight        = 'bold';
			tempP.style.padding           = '3px';
			tempP.style.top               = 0;
			tempP.style.right             = 0;
			tempP.style.cursor            = 'pointer';

			tempDiv.insertBefore(tempP, null);
		}
		else
		{
			$('<A>').css(
			{
				'background'   : "url('http://static.howstuffworks.com/en-us/sm/close-button.gif') no-repeat right",
				'padding-right': "14px",
				'position'     : 'absolute',
				'top'          : '3px',
				'right'        : '4px',
				'cursor'       : 'pointer'
			}).html('Close').appendTo(tempDiv).click(function ()
			{
				me.remove();
			});
		}

		// put it back to static as absolute messes up layout (2/20/2009 MCB)
		if($.browser.msie && parseInt($.browser.version)<=6)
		{
			obj.style.position = 'static';
		}

		this.remove = function()
		{
                        $(tempDiv).remove();

                        // this should be put into function.. Will do later (MCB)
                        if ((typeof options != 'undefined') && (typeof options['hideSelectsFlag'] != 'undefined') && (options['hideSelectsFlag'] == true))
                        {
                                if($.browser.msie && parseInt($.browser.version)<=6)
                                {
                                        $('select').css('visibility', 'visible');
                                }
                        }
			$(document).unbind('click');

			if(typeof options['callBackClose'] == 'function')
			{
				(options['callBackClose'])();
			}
		}

		if (options['closeType'] === 'text')
		{
			$(tempP).click(function(event)
			{
				me.remove();
			});
		}

		// should panel close when we click elsewhere?
		if (options['noCloseOnClick'] !== true)
		{
			setTimeout(function ()
			{
				$(document).unbind('click');
				$(document).click(function (event)
				{
					if(event.target.parentNode.className != 'panelHover')
					{
						me.remove();
					}
				});
			}, 300);
		}

		// post render options (MCB)
		if (options['scroll'])
		{
			if(options['scroll'] == 'down')
			{
				window.scrollTo(0, document.body.offsetHeight);
			}
		}

		if (options['width'])
		{
			tempDiv.style.width = parseInt(options['width']) + 'px';
		}

		if (options['offsetX'])
		{
			tempDiv.style.left = parseInt(tempDiv.style.left) + parseInt(options['offsetX']) + 'px';
		}

		if (options['offsetY'])
		{
			tempDiv.style.top = parseInt(tempDiv.style.top) + parseInt(options['offsetY']) + 'px';
		}
/*
			if (options['absoluteX'])
			{
				tempDiv.style.left = parseInt(options['absoluteX']) + 'px';
			}

			if (options['absoluteY'])
			{
				tempDiv.style.top = parseInt(options['absoluteY']) + 'px';
			}
*/
		if (typeof options['pointerTopImageSource'] !== 'undefined')
		{
			if(!options['pointerTopImageOffsetY'])
			{
				options['pointerTopImageOffsetY'] = '-38px';
			}

			if(!options['pointerTopImageOffsetX'])
			{
				options['pointerTopImageOffsetX'] = '50px';
			}

			$('<img src="'+options['pointerTopImageSource']+'" style="position: absolute; top: '+options['pointerTopImageOffsetY']+'; left: '+options['pointerTopImageOffsetX']+';">').appendTo(tempDiv);
		}
	}

	window.HSW.panelHover = panelHover;
})();
(function ()
{
	var popup =
	{

		popupNode : null,
		_timeout : null,



		popupNodeCreate : function(message)
		{
			popup.popupNode                       = document.createElement('DIV');

			if($.browser.msie && parseInt($.browser.version)<=6)
			{
				popup.popupNode.style.position        = 'absolute';
				popup.popupNode.style.top             = parseInt(event.clientY / 2) + document.documentElement.scrollTop + 'px';
				popup.popupNode.style.left            = document.body.offsetWidth/2 + 'px';
			}
			else
			{
				popup.popupNode.style.position        = 'fixed';
				popup.popupNode.style.top             = '30%';
				popup.popupNode.style.left            = '30%';
			}
			popup.popupNode.style.width           = 'auto';
			popup.popupNode.style.height          = 'auto';
			popup.popupNode.style.backgroundColor = '#0000AF';
			popup.popupNode.style.color           = '#FFFFFF';
			popup.popupNode.style.fontWeight      = 'bold';
			popup.popupNode.style.filter          = 'progid:DXImageTransform.Microsoft.Alpha(opacity=0)';
			popup.popupNode.style.opacity         = 0;
			popup.popupNode.style.zIndex          = 10;
			popup.popupNode.style.padding         = '5px';
			popup.popupNode.style.paddingLeft     = '8px';
			popup.popupNode.style.paddingRight    = '8px';
			popup.popupNode.innerHTML             = message;
			document.body.insertBefore(popup.popupNode, null);
		},

		popupNodeAppend : function(message)
		{
			// oh my ... bad style ... Sorry, I'm in a hurry today .. (MCB)
			if(popup.popupNode.innerHTML.indexOf(message)==-1)
			{
				popup.popupNode.innerHTML += "<br /><br />" + message;
			}
		},

		fade : function()
		{
			var tempOpacity=popup.getOpacity();
			tempOpacity -= 0.1;
			if(tempOpacity > 0)
			{
				popup.setOpacity(tempOpacity);
				popup._timeout = setTimeout(function() {
					popup.fade();
				}, 100);
			}
			else
			{
				document.body.removeChild(popup.popupNode);
				popup.popupNode = null;
				popup._timeout  = null
			}
		},

		getOpacity : function()
		{
			var tempOpacity;
			try
			{
				if(popup.popupNode.filters)
				{
					tempOpacity = popup.popupNode.filters.item('DXImageTransform.Microsoft.Alpha').opacity/100;
				}
				else
				{
					tempOpacity = popup.popupNode.style.opacity;
				}
			}
			catch(e)
			{
			}
			return tempOpacity;
		},

		setOpacity : function(tempOpacity)
		{
			try
			{
				popup.popupNode.filters.item('DXImageTransform.Microsoft.Alpha').opacity = tempOpacity*100;
			}
			catch(e)
			{
				popup.popupNode.style.opacity = tempOpacity;
			}
		},

		show : function(message)
		{
			if (popup.popupNode == null)
			{
				popup.popupNodeCreate(message);
			}
			else
			{
				popup.popupNodeAppend(message);
			}
			if (popup._timeout != null)
			{
				clearTimeout (popup._timeout);
			}

			popup.setOpacity(1);

			popup._timeout = setTimeout(function()
			{
				popup.fade();
			}, 3500); // 2.5 seconds
		}
	}
	HSW.ui.popup = popup
})();
(function ()
{
	HSW.cga.productSelection =
	{
		setup : function (selYear, selMake, selModel, cmdGo)
		{
		
			if(cmdGo)
			{
				// 3-13-09 (Jeff): changed from mousedown to click because
				// expert reviews GO button wasn't firing mousedown event
				$(cmdGo).click( function(e)
				{
					HSW.cga.productSelection.checkGoButton(e, selYear, selMake, this);
				})
				.mousedown( function(e)
				{
					HSW.cga.productSelection.checkGoButton(e, selYear, selMake, this);
				});
			}

//			$(selYear).unbind('change');
			if(selYear)
			{
				$(selYear).change(function()
				{
					var previousMake  = selMake.value;
					var previousModel = selModel.value;

					// if they have selected a year (1/16/2009 MCB)
					// OR have reset it back to the first option (1/16/2009 MCB)
					if (!isNaN(parseInt(selYear.value)) || selYear.selectedIndex == 0)
					{
						$.ajax(
						{
							url      : '/ajax/cga/division-listing-for-year-and-type',
							dataType : 'json',
							data     :
							{
								year : selYear.value,
								type : selYear.getAttribute('type')
							},
							error    : function ()
							{
	     
							},
							success  : function (data)
							{
								$(selMake).children().slice(1).remove();

								for (i=0; i<data.length; i++)
								{
									// jquery doesn't have an elegant way to do this (1/8/2009 MCB)
									// unless you use a plugin (1/8/2008 MCB)
									selMake.options[selMake.options.length] = new Option(data[i].name, data[i].division_id);
								}
								selMake.value  = previousMake;
								if(selMake.value != 0)
								{
									HSW.cga.productSelection.modelsUpdate(selYear, selMake, selModel);
								}
								else
								{
									selModel.selectedIndex = 0;
								}
							}
						});
					}

					if(cmdGo)
					{
						HSW.cga.productSelection.buildGoURL(selYear?selYear.value:null, (parseInt(selMake.value)!=0)?selMake.options[selMake.selectedIndex].innerHTML:0, (parseInt(selModel.value)!=0)?selModel.options[selModel.selectedIndex].innerHTML:0, selYear.getAttribute('type'), (parseInt(selModel.value)!=0)?selModel.options[selModel.selectedIndex].getAttribute('trimOptionsFlag'):0, cmdGo);
					}
				});     
			}

			$(selMake).change(function()
			{
				// if a year is selected (1/13/2009 MCB)
				if(selYear && selYear.selectedIndex>0)
				{
					$.ajax(
					{
						url      : '/ajax/cga/model-listing-for-division-year-and-type',
						dataType : 'json',
						data     :
						{
							divisionId          : selMake.value,
							type                : selMake.getAttribute('type'),
							year                : selYear.value
						},
						error    : function ()
						{
							// what should we do if there is an error? (1/9/2008 MCB)
						},
						success  : function (data)
						{
	
							$(selModel).children().slice(1).remove();
	
							// if there is no model data (1/16/2009 MCB)
							// for this combination (1/16/2009 MCB)
							if(data.length == 0)
							{
								// must pick another year (1/16/2009 MCB)
								selYear.selectedIndex = 0;
							}
							else
							{
								for (i=0; i<data.length; i++)
								{
									var tempOption = new Option(data[i].car_name, data[i].model_id);
									tempOption.setAttribute('trimOptionsFlag', data[i].trimOptionsFlag);
									selModel.options[selModel.options.length] = tempOption;
								}
							}
						}
					});

				}
				else // a year is not selected (1/15/2009 MCB)
				{
					HSW.cga.productSelection.modelsUpdate(selYear, selMake, selModel);
				}

				if(cmdGo)
				{
					HSW.cga.productSelection.buildGoURL(selYear?selYear.value:null, (parseInt(selMake.value)!=0)?selMake.options[selMake.selectedIndex].innerHTML:0, (parseInt(selModel.value)!=0)?selModel.options[selModel.selectedIndex].innerHTML:0, selYear?selYear.getAttribute('type'):null, (parseInt(selModel.value)!=0)?selModel.options[selModel.selectedIndex].getAttribute('trimOptionsFlag'):0, cmdGo);
				}
			});

//			$(selModel).unbind('change');
			$(selModel).change(function()
			{
				if(cmdGo)
				{
					HSW.cga.productSelection.buildGoURL(selYear?selYear.value:null, (parseInt(selMake.value)!=0)?selMake.options[selMake.selectedIndex].innerHTML:0, (parseInt(selModel.value)!=0)?selModel.options[selModel.selectedIndex].innerHTML:0, selYear?selYear.getAttribute('type'):null, (parseInt(selModel.value)!=0)?selModel.options[selModel.selectedIndex].getAttribute('trimOptionsFlag'):0, cmdGo);
				}
			});

			if(selYear)
			{
				selYear.selectedIndex = 0;
			}
			if(selMake)
			{
				selMake.selectedIndex = 0;
			}
//			$(selMake).children().slice(1).remove();
//			$(selModel).children().slice(1).remove();

		}, // end of setup function

		modelsUpdate : function (selYear, selMake, selModel)
		{
			var previousModel = selModel.value;

			////////////////////////////////////////////////////////////
			// this block should be split out to function (1/16/2009 MCB)
			// as it is used in multiple places (1/16/2009 MCB)
			$.ajax(
			{
				url      : '/ajax/cga/model-listing-for-division-year-and-type',
				dataType : 'json',
				data     :
				{
					divisionId : selMake.value,
					type       : selMake.getAttribute('type'),
					year       : selYear?selYear.value:''
				},
				error    : function ()
				{
				},
				success  : function (data)
				{
					$(selModel).children().slice(1).remove();

					// no models available for (1/16/2009 MCB)
					// year division combo...  (1/16/2009 MCB)
					// must choose another make  (1/16/2009 MCB)
					if(data.length == 0)
					{
						selMake.selectedIndex = 0;
						selModel.selectedIndex = 0;
					}
					else
					{
						for (i=0; i<data.length; i++)
						{
							var tempOption = new Option(data[i].car_name, data[i].model_id);
							tempOption.setAttribute('trimOptionsFlag', data[i].trimOptionsFlag);
							selModel.options[selModel.options.length] = tempOption;
						}
					}
					selModel.value = previousModel;
				}
			});
			////////////////////////////////////////////////////////////
		},

		buildGoURL : function (selYear, selMake, selModel, type, trimOptionsFlag, cmdGo)
		{
			if (typeof selMake == 'string')
			{
				selMake  = selMake.toLowerCase();
				selMake  = selMake.replace(' ', '-');
				// remove slashes
				selMake = selMake.replace('/', '-');
			}

			if (typeof selModel == 'string')
			{
				// remove trailing space (1/16/2009 MCB)
				selModel = selModel.replace(/\s+$/, '');
			}	

			$(cmdGo).unbind('click');

			if(parseInt(selYear))
			{
				if(selMake)
				{
					if(selModel)
					{
						if (type == 'new')
						{
							if (typeof selModel == 'string')
							{
								selModel = selModel.toLowerCase();
								// remove NON trailing space with a hyphen (1/22/2009 MCB)
								selModel = selModel.replace(/\s+/g, '-');
								// remove slashes
								selModel = selModel.replace(/\//g, '-');
								// change & to and
								selModel = selModel.replace('&amp;', 'and');
							}

							$(cmdGo).click(function ()
							{
								if(trimOptionsFlag == '1')
								{
									var ff = document.getElementById('frmSelMakeModelNew');
									ff.action = '/' + selYear + '-' + selMake + '-' + selModel + '-trim-options.htm'; 
								}
								else
								{
									var ff = document.getElementById('frmSelMakeModelNew');
									ff.action = '/' + selYear + '-' + selMake + '-' + selModel + '.htm'; 
								}
							});
						}
						else
						{
							selModel = encodeURI(selModel);
							$(cmdGo).click(function ()
							{
								var ff = document.getElementById('frmSelMakeModelUsed');
								ff.action = '/used-' + selMake + '-prices-reviews.htm?model=' + selModel + '&year=' + selYear; 
							});
						}
					}
					else // else no model selected so go to new or used car prices reviews page
					{
						if (type == 'new')
						{
							// This is how Leslie recommended I do this (1/12/2009 MCB)
							$(cmdGo).click(function ()
							{
								var ff = document.getElementById('frmSelMakeModelNew');
								ff.action = '/new-' + selMake + '-prices-reviews.htm?year=' + selYear;
							});
						}
						else
						{
							$(cmdGo).click(function ()
							{
								var ff = document.getElementById('frmSelMakeModelUsed');
								ff.action = '/used-' + selMake + '-prices-reviews.htm?year=' + selYear;
							});
						}
					} 
				} 
			} 
			else // user has not selected a year 
			{
				if(selMake)
				{
					if(type == 'new')
					{	
						if (selModel)
						{
							selModel = encodeURI(selModel);
							$(cmdGo).click(function ()
							{
								var ff = document.getElementById('frmSelMakeModelNew');
								ff.action = '/new-' + selMake + '-prices-reviews.htm?model=' + selModel;
							});
						}
						else
						{
							$(cmdGo).click(function ()
							{
								var ff = document.getElementById('frmSelMakeModelNew');
								ff.action = '/new-' + selMake + '-prices-reviews.htm';
							});
						}
					}
					else if (type == 'used')
					{
						if (selModel)
						{
							selModel = encodeURI(selModel);
							$(cmdGo).click(function ()
							{
								var ff = document.getElementById('frmSelMakeModelUsed');
								ff.action = '/used-' + selMake + '-prices-reviews.htm?model=' + selModel;
							});
						}
						else
						{
							$(cmdGo).click(function ()
							{
								var ff = document.getElementById('frmSelMakeModelUsed');
								ff.action = '/used-' + selMake + '-prices-reviews.htm';
							});
						}
					}
					else // occurs on dropdowns with make and model only
					{
						if(selModel)
						{
							if (typeof selModel == 'string')
							{
								selModel = selModel.toLowerCase();
								// remove NON trailing space with a hyphen (1/22/2009 MCB)
								selModel = selModel.replace(/\s+/g, '-');
								// remove slashes
								selModel = selModel.replace(/\//g, '-');
								// change & to and
								selModel = selModel.replace('&amp;', 'and');
							}

							$(cmdGo).click(function ()
							{
								var ff = document.getElementById('frmSelMakeModelAll');
								ff.action = '/all-' + selMake + '-' + selModel + 's.htm';
							});
							return;
						}

						$(cmdGo).click(function ()
						{
							var ff = document.getElementById('frmSelMakeModelAll');
							ff.action = '/all-' + selMake + '.htm';
						});
					}
				}
				else
				{
				}
			}
		}, // end of buildGoURL (1/15/2009 MCB)

		checkGoButton : function (e, selYear, selMake, sourceElement)
		{
			e.stopPropagation();
			$('.warning').remove();

			// if the interface contains a year drop-down and both year and make are empty (2/12/2009 MCB)
			// OR there is no year drop-down and the make is empty (2/12/2009 MCB)
			if (selMake.value == '0')
			{
				var p = $("<p></p>").addClass('warning').html('Please select a make');
				$(sourceElement.parentNode).append(p);
				$(p).fadeOut(6500);
			}
		}
	}
})();
(function()
{
	HSW.cga.newCarSearch =
	{
		setup : function ()
		{
			// setup new selector interaction (1/7/2008 MCB)
			HSW.cga.productSelection.setup($('#selYearNew')[0], $('#selMakeNew')[0], $('#selModelNew')[0], $('#cmdGoNew')[0]);
			// setup used selector interaction (1/7/2008 MCB)
			HSW.cga.productSelection.setup($('#selYearNewCarTools')[0], $('#selMakeNewCarTools')[0], $('#selModelNewCarTools')[0], null);
	
			$('#newCarQuoteForm').submit(function ()
			{
				var selMake = $('#selMakeNewCarTools')[0];
				var selModel = $('#selModelNewCarTools')[0];
				$('[name=make]').val(selMake.value==''?'':selMake.options[selMake.selectedIndex].innerHTML);
				$('[name=model]').val(selModel.value==''?'':selModel.options[selModel.selectedIndex].innerHTML);
			});
		}
	}

	$().ready(function()
	{
		HSW.cga.newCarSearch.setup();
	});
})();
/* © 2008 HowStuffWorks, Inc. */
// Add this to the HSW namespace defined in hsw.js
$(document).ready(function ()
{
	$('#year >:first').attr('selected', true);
	$('#make').attr('disabled', true);
	$('#make >:first').attr('selected', true);
	$('#model').attr('disabled', true);
	$('#model >:first').attr('selected', true);
	$('#trim').attr('disabled', true);

	// this IF is to prevent failing if compareCars is not available... (1/29/2009 MCB)
	// Eventually, I need to go back and figure out why calls are (1/29/2009 MCB)
	if(HSW.cga.compareCars)
	{
		$('#compareCars').click(HSW.cga.compareCars.navigateToSelectedTrims);

		$('#year').change(HSW.cga.compareCars.changeYear);

		$('#make').change(HSW.cga.compareCars.changeMake);

		$('#model').change(HSW.cga.compareCars.changeModel);
	}

	$('.action > .remove').click(HSW.cga.compareCars.removeCar);
	$('#addToComparison').click(HSW.cga.compareCars.addCar);
});
(function()
{
	HSW.cga.compareCars =
	{
		slotTitles: ['first', 'second', 'third', 'fourth'],
		addCar: function (event)
		{
			event.preventDefault();

			// validation
			if (parseInt($('#year').val()) === 0)
			{
				HSW.cga.compareCars.errorMessage('Please select a year.');
				return;
			}

			if (parseInt($('#make').val()) === 0)
			{
				HSW.cga.compareCars.errorMessage('Please select a make.');
				return;
			}

			if (parseInt($('#model').val()) === 0)
			{
				HSW.cga.compareCars.errorMessage('Please select a model.');
				return;
			}

			if (parseInt($('#trim').val()) === 0)
			{
				HSW.cga.compareCars.errorMessage('Please select a trim.');
				return;
			}

			var emptySlots = $('.selected-cars .empty');
			var carNode = emptySlots.filter(':first');
			var position = $('.selected-cars .item').index(carNode);

			if (emptySlots.size() === 1)
			{
				$('.compare-select-form').slideToggle();
				$('#message').text('You may only select up to 4 vehicles to compare.  To compare another vehicle, remove at least 1 vehicle from your list.');
			}
			else
			{
				$('#message .counter').text(HSW.cga.compareCars.slotTitles[position + 1]);
			}

			carNode.removeClass('empty');
			var model = HSW.cga.makeModelData[$('#year').val()][$('#make').val()].models[$('#model').val()];
			var trim = HSW.cga.trimData[$('#model').val()][$('#trim').val()];
			carNode.children('.photo').append('<a href="' + model.url + '"><img src="http://static.howstuffworks.com/' + trim.image + '" alt="' + $('#trim option:selected').text() + '" /></a>');
			carNode.children('div.action').append('<a class="remove" href="#"><img src="http://static.howstuffworks.com/en-us/consumerguideauto/buttons/remove-button.gif" alt="Remove" /></a>');
			carNode.children('div.action').after('<h4></h4>');
			var title = carNode.children('h4');
			title.append('<a href="' + model.url + '">' + $('#year').val() + ' ' + $('#make option:selected').text() + '</a><br />');
			title.append('<a href="' + model.url + '">' + $('#model option:selected').text() + '</a>');
			carNode.children('.photo').after('<p></p>');
			var trimTitle = carNode.children('p');
			trimTitle.text($('#trim option:selected').text());
			carNode.children('.id').text($('#trim').val());

			// re-bind the action to remove the car
			$('.action > .remove').click(HSW.cga.compareCars.removeCar);

			var count = $('.selected-cars .item:not(.empty)').size();
			if (count > 1)
			{
				$('#compareCars > img').fadeIn();
			}
			else
			{
				$('#compareCars > img').fadeOut();
			}
		},
		removeCar: function (event)
		{
			event.preventDefault();

			var carNode = $(this).parent().parent();
			var position = $('.selected-cars .item').index(carNode);

			var form = $('.compare-select-form:hidden');
			if (form.size() === 1)
			{
				form.slideToggle();
				$('#message').html('Choose your <span class="counter"></span> car.');
			}

			carNode.addClass('empty');

			carNode.children('.photo').empty();
			carNode.children('h4').remove();
			carNode.children('p').remove();
			carNode.children('.id').empty();
			//self destruct
			$(this).remove();

			// If the node being removed is not on the end of the filled slots
			if (position !== $('.selected-cars .item:not(.empty)').size())
			{
				// Shift the empty one to the left and pop it onto the end
				carNode.animate({
					width: "0"
				},
				500,
				function ()
				{
					var clone = carNode.clone();
					carNode.remove();
					clone.removeClass('first');
					clone.removeAttr('style');
					clone.insertBefore('.selected-cars .clearer');

					$('.selected-cars .item:first').addClass('first');
				});
			}

			$('#message .counter').text(HSW.cga.compareCars.slotTitles[$('.selected-cars .item:not(.empty)').size()]);

			var count = $('.selected-cars .item:not(.empty)').size();
			if (count > 1)
			{
				$('#compareCars > img').fadeIn();
			}
			else
			{
				$('#compareCars > img').fadeOut();
			}
		},
		errorMessage: function (message)
		{
			$('#error-message').text(message);
			$('#error-message').show();
			$('#error-message').fadeOut(3500);
		},
		changeYear: function (event)
		{
			var id = $(event.target).attr('id');
			id = id.replace(/[a-zA-Z]+/, '');

			// if this is not a multi-column layout, append nothing to the selector
			if (isNaN (id))
			{
				id = '';
			}

			$('#make' + id).attr('disabled', true);
			$('#make' + id + ' >:first').attr('selected', true);
			$('#model' + id).attr('disabled', true);
			$('#model' + id + ' >:first').attr('selected', true);
			$('#trim' + id).attr('disabled', true);

			if (parseInt($(event.target).val()) === 0)
			{
				return;
			}

			$.getJSON("/ajax/cga/vehicle-listing", {'year': $(event.target).val()},
				function (data)
				{
					HSW.cga.makeModelData[$(event.target).val()] = data;
					var options = '';
					options += '<option value="0">Select Make</option>';
					$.each(data, function (i, item)
					{
						options += '<option value="' + i + '">' + item.name + '</option>';
					});
					$('#make' + id).html(options);
					$('#make' + id).attr('disabled', false);
				}
			);
		},
		changeMake: function (event)
		{
			var id = $(event.target).attr('id');
			id = id.replace(/[a-zA-Z]+/, '');

			// if this is not a multi-column layout, append nothing to the selector
			if (isNaN (id))
			{
				id = '';
			}

			if (parseInt($(event.target).val()) === 0)
			{
				$('#model' + id).attr('disabled', true);
				$('#model' + id + ' >:first').attr('selected', true);
				$('#trim' + id).attr('disabled', true);
				$('#trim' + id + ' >:first').attr('selected', true);
				return;
			}

			var options = '';
			options += '<option value="0">Select Model</option>';
			$.each(HSW.cga.makeModelData[$('#year' + id).val()][$(event.target).val()].models, function (i, item)
			{
				options += '<option value="' + i + '">' + item.name + '</option>';
			});
			$('#model' + id).html(options);
			$('#model' + id).attr('disabled', false);
			$('#trim' + id).attr('disabled', true);
			$('#trim' + id + ' >:first').attr('selected', true);
		},
		changeModel: function (event)
		{
			var id = $(event.target).attr('id');
			id = id.replace(/[a-zA-Z]+/, '');

			// if this is not a multi-column layout, append nothing to the selector
			if (isNaN (id))
			{
				id = '';
			}

			$('#trim' + id).attr('disabled', true);
			$('#trim' + id).html('<option value="0">Select Trim</option>');

			if (parseInt($(event.target).val()) === 0)
			{
				return;
			}

			$.getJSON("/ajax/cga/vehicle-info", {'modelYrId': $(event.target).val()},
			function (data)
			{
				HSW.cga.trimData[$(event.target).val()] = data;
				var options = '';
				options += '<option value="0" selected="selected">Select Trim</option>';
				$.each(data, function (i, item)
				{
					options += '<option value="' + i + '">' + item.name + '</option>';
//					options += '<option value="' + i + '"' + (item.base ? ' selected="selected"' : '') + '>' + item.name + '</option>';
				});
				$('#trim' + id).html(options);
				$('#trim' + id).attr('disabled', false);
			});
		},
		changeModelCompare: function (event)
		{
			var id = $(event.target).attr('id');
			id = id.replace(/[a-zA-Z]+/, '');

			// if this is not a multi-column layout, append nothing to the selector
			if (isNaN (id))
			{
				id = '';
			}

			if (parseInt($(event.target).val()) === 0)
			{
				return;
			}

			$.getJSON("/ajax/cga/vehicle-info", {'modelYrId': $(event.target).val()},
			function (data)
			{
				$.each(data, function (i, item)
				{
					if (item.base === true)
					{
						$('#trim' + id).attr('disabled', false)
						$('#trim' + id).val(i);
						$('#addToComparison' + id).click(HSW.cga.compareCars.navigateToSelectedTrims);
						$('#addToComparison' + id).fadeIn();
						return false;
					}
				});
			});
		},

		changeTrim: function (event)
		{
			event.preventDefault();
			HSW.cga.compareCars.navigateToSelectedTrims();
		},

		navigateToSelectedTrims: function (event)
		{
			// this cancels navigation from clicked anchor tag (2/4/2009 MCB)
			if(event)
			{
				event.preventDefault();
			}
			var trimIds = [];

			var pairs = window.location.search.substring(1).split('&');
			var params = [];
			var data;

			for (i in pairs)
			{
				data = pairs[i].split('=');
				if (data[0] && data[1])
				{
					params[data[0]] = data[1];
				}
			}

			// loop through the trim ids select boxes and get the selected option values
			$('.trim').each(function (i)
			{
				if ($(this).val() != 0)
				{
					trimIds[i] = 'trimIds[' + i + ']=' + $(this).val();
				}
			});

			var qString = trimIds.join('&');

			if (params['type'])
			{
				qString += '&type=' + params['type'];
			}

			// I had to combine two functions... (2/4/2009 MCB)
			// this should be cleaned up eventually (2/4/2009 MCB)
			if(!qString)
			{
				var trimParams = [];
				$('.id').each(function (i)
				{
					i++; // 1-based, not 0-based

					if ($(this).text() !== '')
					{
						trimParams.push('trimIds[]=' + $(this).text());
						qString = trimParams.join('&');
					}
				});
			}

			document.location.href = '/compare-cars-results.htm?' + qString;
		}
	}
})();
