function replaceList(target, json, title, raw) {
	target.children().remove();
	if (json) {
		if (target.prev().children().html() != title) {
			target.prev().children().html(title);
		}
		for(var i = 0; i < json.length; i++) {
			if (!raw) {
				if(typeof json[i].replace == 'function') {
					json[i] = json[i].replace(' ', '&nbsp;');
				}
			}
			$(target).append("<li>" + json[i] + "</li>");
		}
		if($('body#home').size() > 0){
			target.css({'margin-top':0,'width':(target.parent().width() - 2)});	
		}
	} else {
		target.prev().children().html('n/a');
	}
}

function pad_color(n, totalDigits) { 
	n = n.toString(); 
	var pd = ''; 
	if (totalDigits > n.length) { 
		for (i=0; i < (totalDigits-n.length); i++) { 
			pd += '0'; 
		} 
	} 
	return pd + n.toString(); 
} 
function dec2hex( s ) { return ( s<15.5 ? '0' : '' ) + Math.round( s ).toString( 16 ); }
function hex2dec( s ) { return parseInt( s, 16 ); }
function replaceColorList(target, json, title, raw) {
	target.children().remove();
	if (json) {
		if (target.prev().children().html() != title) {
			target.prev().children().html(title);
		}
		for(var i = 0; i < json.length; i++) {
			if (!raw) {
				if(typeof json[i].replace == 'function') {
					json[i] = json[i].replace(' ', '&nbsp;');
				}
			}
			var hexvalue_copy = json[i].HEXVALUE;
			if (json[i].HEXVALUE == '0') {
				json[i].HEXVALUE = '000000';
			} else if (json[i].HEXVALUE == 'FFFFFF') {
				json[i].HEXVALUE = 'FFFFFF; border: 1px solid #000000';
			}
			json[i].HEXVALUE = pad_color(json[i].HEXVALUE, 6);
			$(target).append("<li><span class='color_picker' title='"+json[i].COLOR+"' style='background-color:#"+json[i].HEXVALUE+";'></span><span class='hexvalue'>"+hexvalue_copy+"</span></li>");
		}
		if($('body#home').size() > 0){
			target.css({'width':'93px'});
			var target_height = target.height();
			if (target_height >= 276) {
				if (json.length > 28) {
					target.css({'margin-top':-277});	
				} else {
					target.css({'margin-top':-211});	
				}
			} else {
				if (json.length > 28) {
					target.css({'margin-top':-((target.height() / 3)+ 11)});	
				} else {
					target.css({'margin-top':-(target.height() + 1)});	
				}
			}
		}
	} else {
		target.prev().children().html('n/a');
		$('#home .fancyselect.color, #tires .fancyselect.color, #search .fancyselect.color').animate({'width': 0, 'marginRight': 0});
	}
}

function cleanSpace(txt) {
	if (txt) {
		return txt.replace('&nbsp;', ' ');
	}
}

function reset(target) {
	var o = target.parent().prev();
	if (!o.hasClass('next')) {
		if (o.hasClass('year')) {
			$('#model, #submodel, #color').removeClass('active');
			$('#make').children().html('Make');
			$('#model').children().html('Model');
			$('#submodel').children().html('Submodel');
			$('#color').children().html('Color');
		} else if (o.hasClass('make')) {
			$('#submodel, #color').removeClass('active');
			$('#model').children().html('Model');
			$('#submodel').children().html('Submodel');
			$('#color').children().html('Color');
		} else if (o.hasClass('model')) {
			$('#color').removeClass('active');
			$('#submodel').children().html('Submodel');
			$('#color').children().html('Color');
		} 
	}
}

function attachQuantityListEvents() {
	$('.quantity li').click(function() {
		var o = $(this);
		var s = o.html();
		o.parent().prev().removeClass('error');
		o.parent().prev().children().fadeOut(function() {
			$(this).html(s).fadeIn();
		});
	});
}

function attachStateListEvents() {
	$('.state li').click(function() {
		var o = $(this);
		var s = o.html();
		o.parent().prev().removeClass('error');
		o.parent().prev().children().fadeOut(function() {
			$(this).html(s).fadeIn();
		});
	});
}

function attachYearListEvents() {
	$('.year li').click(function() {
		reset($(this));
		var o = $(this);
		var y = o.html();
		o.parent().prev().removeClass('error');
		$('#zipcode, #year, #make, #model, #submodel, #color').removeClass('next');
		o.parent().prev().children().fadeOut(function() {
			$(this).html(y).fadeIn();
		});
		$('#make').addClass('active').addClass('next');
		replaceList($('#make').next(), [ '<img src="/img/loadingAnimation.gif" class="loading_animation"/>' ], 'Make', true);
		$.post('/ajax/fancyselect.php', { q: 'get_vehicle_makes', year: y }, function(data) { 
			replaceList($('#make').next(), eval(data), 'Make'); 
			attachMakeListEvents();
		});
	});
}

function attachMakeListEvents() {
	$('.make li').click(function() {
		reset($(this));
		var o = $(this);
		var y = $('#year').children().html();
		var m = o.html();
		o.parent().prev().removeClass('error');
		$('#zipcode, #year, #make, #model, #submodel, #color').removeClass('next');
		o.parent().prev().children().fadeOut(function() {
			$(this).html(m).fadeIn();
		});
		$('#model').addClass('active').addClass('next');
		replaceList($('#model').next(), [ '<img src="/img/loadingAnimation.gif" class="loading_animation"/>' ], 'Model', true);
		$.post('/ajax/fancyselect.php', { q: 'get_vehicle_models', year: y, make: cleanSpace(m) }, function(data) { 
			replaceList($('#model').next(), eval(data), 'Model'); 
			attachModelListEvents();
		});
	});
}

function attachModelListEvents() {
	$('.model li').click(function() {
		reset($(this));
		var o = $(this);
		var y = $('#year').children().html();
		var m = $('#make').children().html();
		var mod = o.html();
		o.parent().prev().removeClass('error');
		$('#zipcode, #year, #make, #model, #submodel, #color').removeClass('next');
		o.parent().prev().children().fadeOut(function() {
			$(this).html(mod).fadeIn();
		});

		if ($('#submodel').length > 0) {
			$('#submodel').addClass('active').addClass('next');
			replaceList($('#submodel').next(), [ '<img src="/img/loadingAnimation.gif" class="loading_animation"/>' ], 'Submodel', true);
			$.post('/ajax/fancyselect.php', { q: 'get_vehicle_submodels', year: y, make: cleanSpace(m), model: cleanSpace(mod)}, function(data) { 
				var data = eval(data);
				replaceList($('#submodel').next(), eval(data), 'Submodel'); 
				attachSubModelListEvents();
				if (data.length == 1) {
					$('#submodel').siblings('ul').children().eq(0).click();
					$('#submodel').siblings('ul').children().eq(0).click();
				}
			});
		} else if ($('#color').length > 0) {
			$('#color').addClass('active').addClass('next');
			replaceList($('#color').next(), [ '<img src="/img/loadingAnimation.gif" class="loading_animation"/>' ], 'Color', true);
			populateColorList();
		}
	});
}

function populateColorList() {
	var y = $('#year span').html();
	var m = $('#make span').html();
	var mod = $('#model span').html();
	$.post('/ajax/fancyselect.php', { q: 'get_vehicle_colors', year: y, make: cleanSpace(m), model: cleanSpace(mod)}, function(data) { 
		var data = eval(data);
		replaceColorList($('#color').next(), eval(data), 'Color'); 
		attachColorListEvents();
		if (data.length == 1) {
			$('#color').siblings('ul').children().eq(0).click();
		}
	});

}

function attachSubModelListEvents() {
//	$('#home .fancyselect.color, #tires .fancyselect.color, #search .fancyselect.color').animate({'width': 0, 'marginRight': 0});
	$('.submodel li').click(function() {
		reset($(this));
		var o = $(this);
		var y = $('#year').children().html();
		var m = $('#make').children().html();
		var mod = $('#model').children().html();
		var s = o.html();
		o.parent().prev().removeClass('error');
		$('#zipcode, #year, #make, #model, #submodel, #color').removeClass('next');
		o.parent().prev().children().fadeOut(function() {
			$(this).html(s).fadeIn();
		});
		if ($('#color').length > 0) {
			$('#color').addClass('active').addClass('next');
			replaceList($('#color').next(), [ '<img src="/img/loadingAnimation.gif" class="loading_animation"/>' ], 'Color', true);
			$.post('/ajax/fancyselect.php', { q: 'get_vehicle_colors', year: y, make: cleanSpace(m), model: cleanSpace(mod), submodel: cleanSpace(s)}, function(data) { 
				var data = eval(data);
				replaceColorList($('#color').next(), eval(data), 'Color'); 
				attachColorListEvents();
				if (data != undefined && data.length > 0) {
					$('#home .fancyselect.color, #tires .fancyselect.color, #search .fancyselect.color').animate({'width': 95, 'marginRight': 3});
				}
				if (data!= undefined && data.length == 1) {
					$('#color').siblings('ul').children().eq(0).click();
				}
			});
		}
	});
}

function attachColorListEvents() {
	$('.color li').click(function() {
		reset($(this));
		var o = $(this);
		var y = $('#year').children().html();
		var m = $('#make').children().html();
		var mod = $('#model').children().html();
		var submod = $('#submodel').children().html();
		var c = o.html();
		var title = o.children().attr('title');
		o.parent().prev().removeClass('error');
		$('#zipcode, #year, #make, #model, #submodel, #color').removeClass('next');
		o.parent().prev().children().fadeOut(function() {
//			$(this).css({marginLeft: '-10px'});
			$(this).html(c).append("<span class='color_title'>"+title+"</span>").fadeIn();
		});
	});
}

function attachCrossSectionEvents() {
	$('.cross_section li').click(function() {
		reset($(this));
		var o = $(this);
		var cs = o.html();
		o.parent().prev().removeClass('error');
		$('#cross_section, #aspect_ratio, #rim_diameter').removeClass('next');
		o.parent().prev().children().fadeOut(function() {
			$(this).html(cs).fadeIn();
		});
		$('#aspect_ratio').addClass('active').addClass('next');
		replaceList($('#aspect_ratio').next(), [ '<img src="/img/loadingAnimation.gif" class="loading_animation"/>' ], 'Aspect Ratio', true);
		$.post('/ajax/fancyselect.php', { q: 'get_vehicle_aspect_ratios', cross_section: cs }, function(data) { 
			replaceList($('#aspect_ratio').next(), eval(data), 'Aspect Ratio', true); 
			attachAspectRatioEvents();
		});
	});
}

function attachAspectRatioEvents() {
	$('.aspect_ratio li').click(function() {
		reset($(this));
		var o = $(this);
		var cs = $('#cross_section').children().html();
		var ar = o.html();
		o.parent().prev().removeClass('error');
		$('#cross_section, #aspect_ratio, #rim_diameter').removeClass('next');
		o.parent().prev().children().fadeOut(function() {
			$(this).html(ar).fadeIn();
		});
		$('#rim_diameter').addClass('active').addClass('next');
		replaceList($('#rim_diameter').next(), [ '<img src="/img/loadingAnimation.gif" class="loading_animation"/>' ], 'Rim Diameter', true);
		$.post('/ajax/fancyselect.php', { q: 'get_vehicle_rim_diameters', cross_section: cs, aspect_ratio: ar }, function(data) { 
			replaceList($('#rim_diameter').next(), eval(data), 'Rim Diameter', true); 
			attachRimDiameterEvents();
		});
	});
}

function attachRimDiameterEvents() {
	$('.rim_diameter li').click(function() {
		reset($(this));
		var o = $(this);
		var cs = $('#cross_section').children().html();
		var ar = $('#aspect_ratio').children().html();
		var rd = o.html();
		o.parent().prev().removeClass('error');
		$('#aspect_ratio').removeClass('next');
		o.parent().prev().children().fadeOut(function() {
			$(this).html(rd).fadeIn();
		});
		$('#zipcode_2').addClass('active').addClass('next');
	});
}

function attachTireBrandListEvents() {
	$('.tires_brand li').click(function() {
		reset($(this));
		var o = $(this);
		var brand = o.html();
		o.parent().prev().removeClass('error');
		o.parent().prev().children().fadeOut(function() {
			$(this).html(brand).fadeIn();
		});
		replaceList($('#tires_model').next(), [ '<img src="/img/loadingAnimation.gif" class="loading_animation"/>' ], 'Select Brand', true);
		$.post('/ajax/fancyselect.php', { q: 'get_tire_models', 'tire_brand': brand }, function(data) { 
			var data = eval(data);
			replaceList($('#tires_model').next(), eval(data), 'Select Brand'); 
			$('#tires_model').addClass('active').addClass('next');
			attachTireModelListEvents();
			if (data != undefined && data.length == 1) {
				$('#tires_model').siblings('ul').children().eq(0).click();
				$('#tires_model').siblings('ul').children().eq(0).click();
			}
		});
	});
}

function attachTireModelListEvents() {
	$('.tires_model li').click(function() {
		reset($(this));
		var o = $(this);
		var mod = o.html();
		o.parent().prev().removeClass('error');
		o.parent().prev().children().fadeOut(function() {
			$(this).html(mod).fadeIn();
		});
	});
}

function attachWheelBrandListEvents() {
	$('.wheels_brand li').click(function() {
		reset($(this));
		var o = $(this);
		var mod = o.html();
		o.parent().prev().removeClass('error');
		o.parent().prev().children().fadeOut(function() {
			$(this).html(mod).fadeIn();
		});
		replaceList($('#wheels_model').next(), [ '<img src="/img/loadingAnimation.gif" class="loading_animation"/>' ], 'Select Brand', true);
		$.post('/ajax/fancyselect.php', { q: 'get_wheels_models' }, function(data) { 
			var data = eval(data);
			replaceList($('#wheels_model').next(), eval(data), 'Select Brand'); 
			attachWheelModelListEvents();
			if (data.length == 1) {
				$('#wheels_model').siblings('ul').children().eq(0).click();
			}
		});
	});
}

function attachWheelModelListEvents() {
	$('.wheels_model li').click(function() {
		reset($(this));
		var o = $(this);
		var mod = o.html();
		o.parent().prev().removeClass('error');
		o.parent().prev().children().fadeOut(function() {
			$(this).html(mod).fadeIn();
		});
	});
}

function attachZipCodeEvents() {
	$('#zipcode, #year, #mileage').one('click', function() {
		if ($(this).attr('id') == 'year') {
			replaceList($('#year').next(), [ '<img src="/img/loadingAnimation.gif" class="loading_animation"/>' ], 'Year', true);
		}
		if ($('#year span').html() == 'Year') {
			$.post('/ajax/fancyselect.php', { q: 'get_vehicle_years' }, function(data) {
				replaceList($('#year').next(), eval(data), 'Year', true);
				attachYearListEvents();
			});
		}
	});
}

function attachTiresBrandEvents() {
	$('#tires_brand').one('click', function() {
		replaceList($('#tires_brand').next(), [ '<img src="/img/loadingAnimation.gif" class="loading_animation"/>' ], 'Brand', true);
		$.post('/ajax/fancyselect.php', { q: 'get_tire_brands' }, function(data) {
			replaceList($('#tires_brand').next(), eval(data), 'Brand', true);
			attachTireBrandListEvents();
		});
	});
}


$(document).ready(function() {
	if ($('body#tires').length > 0) {
		reIndex();
		$('body#tires .fancyselect.color').css({'zIndex': ''});
	}

	$('.car_image').attr('src')

	hideColorSelectorIfTheValueIsMissing();

	attachHoverEventToMissingVehicleIfItExists();

//	attachShowTireHover();

	$('.vehicle_small').click(function() {
		var year = $.cookie('cookie_year');
		var make = $.cookie('cookie_make');
		var model = $.cookie('cookie_model');
		var submodel = $.cookie('cookie_submodel');
		var color = $.cookie('cookie_color');

		var fancyselect_year = $('#year span').html();
		var fancyselect_make = $('#make span').html();
		var fancyselect_model = $('#model span').html();
		var fancyselect_submodel = $('#submodel span').html();
		var fancyselect_color = $('#color span').html();
		if (fancyselect_year.length > 0 && fancyselect_year != 'Year') { year = fancyselect_year; }
		if (fancyselect_make.length > 0 && fancyselect_make != 'Make') { make = fancyselect_make; }
		if (fancyselect_model.length > 0 && fancyselect_model != 'Model') { model = fancyselect_model; }
		if (fancyselect_submodel.length > 0 && fancyselect_submodel !='Submodel') { submodel = fancyselect_submodel; }
		if (fancyselect_color.length > 0 && fancyselect_color != 'Color') { color = fancyselect_color; }
		if (fancyselect_color.length > 6 && fancyselect_color != 'Color') { color = $('#color span span.hexvalue').html(); }

		window.location = '/tires/search/' + year + '/' + make + '/' + model + '/' + submodel + '/' + color + '/';
	});
	$('#zipcode, #zipcode_2').focus(function() { 
		if ($(this).val() == 'ZIP') { $(this).val(''); } 
	})
	if ($('#zipcode').size() > 0){
		$('#zipcode').blur(function() { 
			var value = $(this).val();
			if (value == '') { 
				$(this).val('ZIP'); 
			} else if (value.length < 5) {
				$('#zipcode').parent().addClass('error');
				$('#year, #make, #model, #submodel, #color').removeClass('active').removeClass('next').removeClass('error');			
			}else {
				$('#zipcode, #year, #make, #model, #submodel, #color').removeClass('next').removeClass('error');
				$('#zipcode').parent().removeClass('error');
				$('#year').addClass('active').addClass('next');
			}
		});
	}else{
		$('#zipcode, #year, #make, #model, #submodel, #color').removeClass('next').removeClass('error');
		$('#zipcode').parent().removeClass('error');
		$('#year').addClass('active').addClass('next');
	}
	$('#year').addClass('active').addClass('next');
	$('#tires_brand').addClass('active').addClass('next');

	$('#cross_section').one('click', function() {
		$.post('/ajax/fancyselect.php', { q: 'get_vehicle_cross_sections' }, function(data) {
			replaceList($('#cross_section').next(), eval(data), 'Cross Section', true);
			attachCrossSectionEvents();
		});
	});

	$('#size_search_alternative').one('click', function() {
		$('#cross_section').click();
	});

	attachQuantityListEvents();
	attachZipCodeEvents();
	attachStateListEvents();
	attachYearListEvents();
	attachMakeListEvents();
	attachModelListEvents();
	attachSubModelListEvents();
	attachTireBrandListEvents();
	attachWheelBrandListEvents();
	attachTiresBrandEvents();

/*
	attachCrossSectionEvents();
	attachAspectRatioEvents();
	attachRimDiameterEvents();
*/


/*
	$('#zipcode, #zipcode_2').keypress(function(event) {
		if (event.which == 13) {
			event.preventDefault();	
		}
	});
*/
	
	$('.toprow #zipcode').keypress(function(event) {
		if (event.keyCode == '13') { 
			$(this).parent().parent().parent().submit();
		}
	});

	
	$('#redbutton').click(function(event) {
		$('#search_by_vehicle').submit();
	});

	$('#search_by_vehicle').submit(function(event) {
		var zipcode = $('#zipcode').val();
		var year = $('#year').children().html();
		var make = $('#make').children().html();
		var model = $('#model').children().html();
		var submodel = $('#submodel').children().html();
		var color = $('#color:visible').children().html();
		if (color == 'Color' || color == undefined) {
			color = '';
		} else {
			color = $('#color').children().children('.hexvalue').html()
		}

		if (zipcode.length == 5 && year != 'Year' && make != 'Make' && model  != 'Model' && submodel  != 'Submodel') { 
			$('#zipcode_hidden').val(zipcode);
			var year = $('#year_hidden').val(year).val();
			var make = $('#make_hidden').val(cleanSpace(make)).val();
			var model = $('#model_hidden').val(cleanSpace(model)).val();
			var submodel = $('#submodel_hidden').val(cleanSpace(submodel)).val();	
			if (color != undefined && color.length > 0) {
				var color = $('#color_hidden').val(cleanSpace(color)).val();
			}
			$('.search_error').fadeOut(function() { 
				set_vehicle_cookie(year, make, model, submodel, color);
				$('.error').removeClass('error');
				wheelsTracker.trackEvent('ButtonClicks', 'Search by vehicle');
			});
		}
		else {
			if (zipcode.length < 5) { $('#zipcode').parent().addClass('error'); $('.search_error').fadeIn(); }
			if (year == 'Year') { $('#year').addClass('error'); $('.search_error').fadeIn(); }
			if (make == 'Make') { $('#make').addClass('error'); $('.search_error').fadeIn(); }
			if (model == 'Model') { $('#model').addClass('error'); $('.search_error').fadeIn(); }
			if (submodel == 'Submodel') { $('#submodel').addClass('error'); $('.search_error').fadeIn(); }
			return false;
		}
	});

	$('#redbutton_2').click(function() {
		var cross_section = $('#cross_section').children().html();
		var aspect_ratio = $('#aspect_ratio').children().html();
		var rim_diameter = $('#rim_diameter').children().html();
		var zipcode_2= $('#zipcode_2').val();
		if ( cross_section != 'Cross Section' &&
			 aspect_ratio != 'Aspect Ratio' &&
			 rim_diameter != 'Rim Diameter' &&
			zipcode_2.length == 5) {

			$('#cross_section_hidden').val($('#cross_section').children().html());	
			$('#aspect_ratio_hidden').val(cleanSpace($('#aspect_ratio').children().html()));
			$('#rim_diameter_hidden').val(cleanSpace($('#rim_diameter').children().html()));	
			$('#zip_code_2_hidden').val($('#zipcode_2').val());
			$('.search_error_size').fadeOut(function() {
				$('.error').removeClass('error');
				wheelsTracker.trackEvent('ButtonClicks', 'Search by size');
				$('#search_by_size').submit();
			});
		}

		if (zipcode_2.length < 5) { $('#zipcode_2').parent().addClass('error'); $('.search_error_size').fadeIn();}
		if (cross_section == 'Cross Section') { $('#cross_section').addClass('error'); $('.search_error_size').fadeIn();}
		if (aspect_ratio == 'Aspect Ratio') { $('#aspect_ratio').addClass('error'); $('.search_error_size').fadeIn();}
		if (rim_diameter == 'Rim Diameter') { $('#rim_diameter').addClass('error'); $('.search_error_size').fadeIn();}
	});


	cookie();

});

function cookie() {
	var year = $.cookie('cookie_year');
	var make= $.cookie('cookie_make');
	var model= $.cookie('cookie_model');
	var submodel= $.cookie('cookie_submodel');
	var color= $.cookie('cookie_color');

	if (year != undefined && year.length > 0) {
		var data = {
			'ajax': 'get_vehicle_image_large',
			'speed_optimizer': 'my_wheel_works,MyWheelWorks',
			'year': year,
			'make': make,
			'model': model,
			'submodel': submodel,
			'color': color
		};
/*
		$.ajax({
			url: '/',
			data: data,
			dataType: 'json',
			success: function(json) {
				var img = $(document.createElement('img')).attr('id', 'hidden_large_image').attr('src', json[0]).appendTo('body');
			}
		});
*/
	}
}

function get_large_vehicle_image() {
	var image = $('#hidden_large_image').attr('src');
	return image;
}
	
function set_vehicle_cookie(year, make, model, submodel, color) {
	var options = { path: '/', expires: 30 };
	$.cookie('cookie_year', year, options);
	$.cookie('cookie_make', make, options);
	$.cookie('cookie_model', model, options);
	$.cookie('cookie_submodel', submodel, options);
	$.cookie('cookie_color', color, options);
}

function attachHoverEventToMissingVehicleIfItExists() {
	var car_image_source = $('.car_image').attr('src');
	if (car_image_source != undefined) {
		var missing_car = car_image_source.search(/missing/);
		if (missing_car != -1) { 
			$('.car_image').hover(function() {
				$(this).fadeOut(function() {
					$(this).parent().addClass('tire_background');
					$('.tire_background').animate({'backgroundPosition': '0 27px'});

					$('.tire_background').hover(function() {
						$('.tire_background').stop().animate({'backgroundPosition': '0 57px'});
					}, function() {
						$('.tire_background').stop().animate({'backgroundPosition': '0 27px'});
					});

				});
			});

		}
	}
}

function hideColorSelectorIfTheValueIsMissing() {
	var hexvalue = $('#color .hexvalue').html();
	if (hexvalue != undefined && hexvalue.length == 0) {
		$('#home .fancyselect.color, #tires .fancyselect.color, #search .fancyselect.color').animate({'width': 0, 'marginRight': 0});
	}
	
}

function attachShowTireHover() {
	$('.tire_image').hover(function() {
		$(this).animate({'height': $(this).children('img').height()});
	}, function() {
		$(this).animate({'height': '30px'});
	});
}



