// Properties
//var dataStoreUrl = "/Team_Michelin_HTMLs/flash/assets/en/videos/";
//var fileExtension = ".mp4";
siteUrl="/assets/mi/system";

var flashSupport = true;
var flashVersion = 0;
var stepHeading;
var stepDesc;
var stepOther;
var isBackAction = false;
var limit = 25;

var performanceHelpText = { 
     "Handling"   			 :   "The responsiveness, control or feel, of the vehicle.", 
     "Fuel Efficiency"       :   "Low rolling resistance, or ease with which a tire rolls on pavement, resulting in better fuel efficiency.", 
     "Comfort"				 :   "The tire's ability to provide a cushioned ride by absorbing shocks and bumps on the road.",
	 "Wear Life" 			 :	 "The usable life of the tread.",
	 "Braking" 				 :   "The tire's ability to grip the surface when braking, bringing the vehicle to a stop more quickly.",
	 "Off Road"				 :   "The tire's overall ability to perform when driven on dirt or other loose and natural surfaces.",
	 "Snow Traction" 		 :   "The tire's ability to grip the surface in snowy conditions.",
	 "Ice Traction" 		 :   "The tire's ability to grip the surface in icy conditions."
};

var priorityDisplay = {
	"1"		: "Highest Priority",
	"2"		: "2nd Priority",
	"3"		: "3rd Priority",
	"4"		: "4th Priority",
	"5"		: "5th Priority"
}

var pageNameList = {
	"2"		: "Team Michelin - Driving Conditions",
	"3"		: "Team Michelin - Runflat",
	"4"		: "Team Michelin - Tire Category",
	"5"		: "Team Michelin - Vehicle Use",
	"6"		: "Team Michelin - Sidewall"
}

var optionsMapping = {
	"BSW"			:	"1",
	"WSW"			:	"2",
	"ORWL"			:	"3",
	"RWL"			:	"4",
	"Summer"		:	"1",
	"Winter"		:	"2",
	"All Season"	:	"3",
	"Runflat"		:	"1",
	"non-Runflat"	:	"2",
	"P"				:	"1",
	"L"				:	"2"
}
// Methods
function getQueryString(name) {
	var result = "";
	
	var regex = new RegExp( "[\\?&]" + name + "=([^&#]*)" );
	var match = location.search.match(regex);
	
	if (match != null) {
		result = decodeURIComponent(match[0]);
		result = result.substring(result.indexOf("=") + 1);
	}
		
	return result;
}

function dropdownScroll(sender, step, count) {
	if (!$(sender).parent().find(".scroll-parent").is(":visible")) return;
	
	if ((step == null) || (step == 0))
		step = ($(sender).find("li:first").length > 0) ? $(sender).find("li:first").outerHeight() : 50;
	if ((count == null) || (count == 0))
		count = 1;
	
	var top = eval($(sender).css("margin-top").replace("px", "")) + (count * step);
	var visible = $(sender).parent().height();
	var total = $(sender).height();
	
	if (top > 0)
		top = 0;
	if (top < visible - total)
		top = visible - total;
					
	$(sender).stop().animate({ "margin-top": top }, 500);
	$(sender).parent().find(".scroll-bar").find("a").stop().animate({ bottom: (100 - Math.round((top / (visible - total)) * 100)) + "%" }, 500);
}

function compileResults(target) {
	var queryString = "";
	
	$("li[id^='step_']").each(function() {
		var name = $(this).find("a").attr("href").substring(1);
		
		if (name.indexOf("?") > 0)
			name = name.substring(name.indexOf("?") + 1, name.indexOf("="));
		
		var value = "";

		$(this).find("input[type='hidden']").each(function() {
			if ($(this).val().length > 0)
				value += ((value.length > 0) ? " " : "") + $(this).val();
		});

		queryString += ((queryString.length > 0) ? "&" : "") + name + "=" + encodeURIComponent(value);
	});
	
	window.location = target + "?" + queryString;
}

// Home Page Init
function homePageGuideSearchUpdate(sender) {
	if ($(sender).parents("#vehicle").length > 0)
		if ($("#find_tire_link").hasClass("current")) {
			var value = "";
		
			$(sender).parents("#vehicle").find("input[type='hidden']").each(function() {
				if ($(this).val().length > 0)
					value += ((value.length > 0) ? " " : "") + $(this).val();
			});
		}
}

function homePageInit() {
	// Init Tooltips
	$(".driver_btn").mouseenter(function(){
		$(".driver").show();
	}).mouseleave(function(){
		$(".driver").hide();
	});
	$(".engineer_btn").mouseenter(function(){
		$(".engineer").show();
	}).mouseleave(function(){
		$(".engineer").hide();
	});
	$(".designer_btn").mouseenter(function(){
		$(".designer").show();
	}).mouseleave(function(){
		$(".designer").hide();
	});
	$(".read_advice").mouseenter(function(){
		$(".read_text").show();
	}).mouseleave(function(){
		$(".read_text").hide();
	});
	$(".play_advice").mouseenter(function(){
		$(".video_text").show();
	}).mouseleave(function(){
		$(".video_text").hide();
	});
	$(".logo_advice").mouseenter(function(){
		$(".logo_text").show();
	}).mouseleave(function(){
		$(".logo_text").hide();
	});
	$(".quick_advice").mouseenter(function(){
		$(".search_text").show();
	}).mouseleave(function(){
		$(".search_text").hide();
	});
	
	// Init Tabs
	$(".home_tabs > li > a").click(function() {
	
		$(this).parents("ul").find("a.current").removeClass("current");
		$(this).addClass("current");
		
		var index = $(this).parent().index();
		
		$(".home_steps.show").removeClass("show");
		$(".home_steps").eq(index).addClass("show");
		
		$(this).parents("div:first").find(".tab_text.show").removeClass("show");
		$(this).parents("div:first").find(".tab_text").eq(index).addClass("show");
		if($(this).html() =="Tire<br> Category")
		{
		 $("#category").find(".drop-down").addClass("show");
		}
		if($(this).html() =="Tire Name")
		{
		 $("#name").find(".drop-down").addClass("show");
		}
	});
	
	// Init Buttons
	$("#home_info a.quick_advice, #find_tire_link").click(function(e) {
		if (!$(this).hasClass("current")) return false;
	});
	
	//Code to open winter popup
	
	
	
	
	$("#winter_body a.sprite2").click(function() {
		$.fancybox.close();
	});
	
	// Bind Content
	homePageContentInit(homePageGuideSearchUpdate,'');
	
	// Prepopulate YMMO if passed by a parameter
	var ymmo = getQueryString("ymmo");
	
	//Cookie ymmo value
	var cookieYmmo;
	var cookieSize;
	if(ymmo == null || ymmo.length <= 0){
		if($.cookie('type') != null || $.cookie('type') != '')
		{
			if($.cookie('type') =='vehicle')
			{
				var yearCookie	= $.cookie('year');
				var makeCookie	= $.cookie('make');
				var modelCookie	= $.cookie('model');
				var optionsCookie	= $.cookie('options');
				var tireSizeCookie = $.cookie('tireSize');
				cookieYmmo = ","+yearCookie+","+makeCookie+","+modelCookie+","+optionsCookie;
				if(tireSizeCookie != null )
					cookieYmmo = ","+cookieYmmo+","+tireSizeCookie;
				$(".link1").click();
				ymmo = cookieYmmo;
				if ((ymmo != null) && (ymmo.length > 0))
					$("#vehicle .option .drop-down").each(function() {
						var match = "";
						$(this).find("li").each(function() {
						if ((ymmo.indexOf(","+$(this).text()) != -1) && ($(this).text().length > match.length)) {
								$(this).trigger("click");
								match = $(this).text();
							}
						});
					});
					
					$('#vehicleSubmit').live('click', function() {
					checkForWinter('vehicle');
				  // Live handler called.
				});
			}
			else if($.cookie('type') =='size')
			{
				var sizeCookie = $.cookie('size');
				var widthCookie = $.cookie('width');
				var aspectratioCookie = $.cookie('aspectratio');
				var diameterCookie = $.cookie('diameter');
				cookieSize = sizeCookie+" "+widthCookie+" "+aspectratioCookie+" "+diameterCookie;
				$(".link2").click();
				var oriStr;
				if ((cookieSize != null) && (cookieSize.length > 0))
					$("#sizetab .option .drop-down").each(function() {
						var match = "";
						$(this).find("li").each(function() {
						if(isNaN($(this).text()))
							oriStr = ($(this).text()).toLowerCase().replace(/^[\r\n]+|[\r\n]+$/g, "").substring(0,(($(this).text()).indexOf("(")-1));
						else
							oriStr = $(this).text();
						if ((cookieSize.indexOf(oriStr) != -1) && (oriStr.length > match.length)) {
								$(this).trigger("click");
								
								match = oriStr;
								
							}
						});
					});
				$('#sizeSubmit').live('click', function() {
					checkForWinter("size");
					// Live handler called.
				});
			}
			else if($.cookie('type') =='name')
			{
				var nameCookie = $.cookie('name');
				$(".link3").click();
				$("#name .option .drop-down").find("li").each(function() {
					if($(this).text().replace('\u00E9', 'e').toLowerCase().replace(/\//g,'-').replace(/[^a-zA-Z0-9\s-]/g,'').replace(/\s/g,'-') == nameCookie){
					$(this).trigger("click");
					}
				});
				
			}
			else if($.cookie('type') =='category')
			{
				var categoryCookie = $.cookie('category');
				 $(".link4").click();
				 $("#category .option .drop-down").find("li").each(function() {
					if($(this).text().replace('\u00E9', 'e').toLowerCase().replace(/\//g,'-').replace(/[^a-zA-Z0-9\s-]/g,'').replace(/\s/g,'-') == categoryCookie){
					$(this).trigger("click");
					}
				});
			}
		}
	}
	else {
		// Prepopulate YMMO if passed by a parameter
	
		if ((ymmo != null) && (ymmo.length > 0))
			$("#vehicle .option .drop-down").each(function() {
				var match = "";
				$(this).find("li").each(function() {
				if ((ymmo.indexOf($(this).text()) != -1) && ($(this).text().length > match.length)) {
						$(this).trigger("click");
						match = $(this).text();
					}
				});
			});
	}
}

// Step 1 Init
function step1Init() {
	//Bind country dropdown
	$(".country_form").click(function(){
		$(this).parents(".callme_dropdown").find(".drop-down").show();
	});
	
}

// Step 2 Init
function step2Init() {
	// Bind Content
	step2ContentInit();

	// Bind Item Select	
	$(".driving_conditions .driving_select li a").click(function() {
		$(this).parents("ul:first").find("a.selected").removeClass("selected");
		
		$("input[type='hidden'][name='Driving-Conditions']").val($(this).find(".text").text());
		
		$(this).addClass("selected");
		$(this).parents(".vehicle_info").find(".next_btn").addClass("current");
	});
}

// Step 3 Init
function step3Init() {
	// Bind Content
	step3ContentInit();

	// Bind Item Select	
	$(".runflats .runflat_select li a").click(function() {
		$(this).parents("ul:first").find("a.selected").removeClass("selected");
		
		$("input[type='hidden'][name='Runflat']").val($(this).find(".text").text());
		
		$(this).addClass("selected");
		$(this).parents(".vehicle_info").find(".next_btn").addClass("current");
	});
}

// Step 4 Init
function step4Init() {
	// Bind Content
	step4ContentInit();

	// Bind Item Select	
	$(".tire_category .priority_select li a").click(function() {
		$(this).parents("ul:first").find("a.selected").removeClass("selected");
		
		$("input[type='hidden'][name='Tire-Category']").val($(this).find(".text").text());
		
		$(this).addClass("selected");
		$(this).parents(".vehicle_info").find(".next_btn").addClass("current");
	});
}

// Step 5 Init
function step5Init() {
	// Bind Content
	step5ContentInit();

	// Bind Item Select	
	$(".vehicle_use .priority_select li a").click(function() {
		$(this).parents("ul:first").find("a.selected").removeClass("selected");
		$("input[type='hidden'][name='Vehicle-Use']").val($(this).find(".hide").text());
		
		$(this).addClass("selected");
		$(this).parents(".vehicle_info").find(".next_btn").addClass("current");
	});
}

// Step 6 Init
function step6Init() {
	// Bind Image Zoom
	$(".sidewall .sidewall_select li .magnify").click(function() {
		var imageUrl = $(this).attr("rel");
		
		showModal("#sidewall_modal");
		$("#sidewall_modal").find("img").remove();
		
		var img = new Image();
		
		$(img)
			.load(function() {
				$("#sidewall_modal").append(this);
			})
			.attr('src', imageUrl);		
	});
	
	$(".sidewall .sidewall_select li a:not('.magnify')").click(function() {
		$(this).parents("ul:first").find("a.selected").removeClass("selected");
		$("input[type='hidden'][name='Tire-Sidewall']").val($(this).find(".text").text());
		
		$(this).parents("li:first").find("a").addClass("selected");
		$(this).parents(".vehicle_info").find(".next_btn").addClass("current");
	});
}

// Step 7 Init
function step7Init() {
	$('.performance .vehicle_info #draggable .ui-state-default').each(function(index) {
		$('.performance .vehicle_info .question_list li:nth-child('+(index+1)+')').find('span .hint_text').text(performanceHelpText[$(this).find('span').text()]);
	});
	// Bind Content
	step7ContentInit();
}

function initDragDrop() {
	var count = 0;
	
	$("#draggable li").draggable({
		connectToSortable: "#droppable",
		containment: "#preference",
		cancel: ".ui-draggable-dropped",
		helper: "clone",
		start:	function(sender, e) {
					count = $("#droppable li").length;
				},
		stop:	function(sender, e) {
					if ($("#droppable li").length > count)
						$(this).draggable( "option", "disabled", true );
				}
	}).disableSelection();
	
	$("#draggable .ui-state-default").dblclick(switchLists);
	
	$( "#droppable" ).sortable({
		revert: true,
		connectWith: "#draggable",
		"receive":	function(sender, e) {
						var item = null;
						var target = $(this);
						
						$(target).children().each(function() {
							if ($(this).text() == $(e.item).text())
								item = $(this);
						});
						
						$(item).addClass("ui-state-highlight");
						$(e.sender).addClass("ui-draggable-dropped")
								   .draggable( "option", "disabled", true );	
								   
						// Activate Next button if more than 1 option is selected
						if ($(target).children().length == 1)
							$(target).parents(".vehicle_info").find(".next_btn").addClass("current");
							
						// Update Hidden Field
						var values = $("input[type='hidden'][name='Performance-Preferences']").val();
						
						if (values.indexOf($(item).find("span:first").text()) < 0)
							values += ((values.length > 0) ? "," : "") + $(item).find("span:first").text();
							
						$("input[type='hidden'][name='Performance-Preferences']").val(values);
					},
		"update":	function(sender, e) {
						// Update Hidden Field
						var values = "";
						
						var target = $(this);
						
						$(target).children().each(function() {
							values += ((values.length > 0) ? "," : "") + $(this).find("span:first").text();
						});
						
						$("input[type='hidden'][name='Performance-Preferences']").val(values);
					},
		"stop":		function(sender, e) {
						if ($(e.item).attr("remove") == "true")
							$(e.item).remove();
					}
	}).disableSelection();
	
	$("#draggable").droppable({
		drop: 	function(sender, e) {
					var item = null;
					var sender = $(e.draggable).parent();
					var target = $(this);
					
					if ($(sender).attr("id") != $(target).attr("id")) {
						$(target).children().each(function() {
							if ($(this).text() == $(e.draggable).text())
								item = $(this);
						});
						
						$(item).removeClass("ui-draggable-dropped")
							   .draggable( "option", "disabled", false );
					
						// Update Hidden Field
						var values = $("input[type='hidden'][name='Performance-Preferences']").val();
						
						if (values.indexOf($(item).find("span:first").text()) > 0)
							values = values.replace("," + $(item).find("span:first").text(), "");
						else if (values.indexOf($(item).find("span:first").text()) == 0)
							if (values.length == $(item).find("span:first").text().length)
								values = "";
							else
								values = values.replace($(item).find("span:first").text() + ",", "");
							
						$("input[type='hidden'][name='Performance-Preferences']").val(values);
						
						// Remove item from the source list
						$(e.draggable).attr("remove", "true");
						$(e.draggable).remove();
						
						// Deactivate Next button if no option is selected
						if ($(sender).children().length <= 1)
							$(target).parents(".vehicle_info").find(".next_btn").removeClass("current");
					}
			}
	});
	
	//$("input[type='hidden'][name='Performance-Preferences']").val("");
}
	
function switchLists(e) {
	var target = $("#draggable,#droppable").not($(e.currentTarget).parent());

	var item = $(e.currentTarget).clone();

	var exists = false;	
	$(target).children().each(function() {
		if ($(item).text() == $(this).text())
			exists = true;
	});
	
	if (!exists)
		target.append(item);
		
	$(item).addClass("ui-state-highlight");

	$(e.currentTarget).addClass("ui-draggable-dropped")
			   		  .draggable( "option", "disabled", true );	

	// Activate Next button if more than 1 option is selected
	if ($(target).children().length == 1)
		$(target).parents(".vehicle_info").find(".next_btn").addClass("current");
		
	// Update Hidden Field
	var values = $("input[type='hidden'][name='Performance-Preferences']").val();
	
	if (values.indexOf($(item).find("span:first").text()) < 0)
		values += ((values.length > 0) ? "," : "") + $(item).find("span:first").text();
		
	$("input[type='hidden'][name='Performance-Preferences']").val(values);
}
	
// Activate step
function gotoStep(step, animate) {
	var newStep = $("li.tire_selector").eq(step - 1);

	// Show next step
	$(newStep).fadeIn(animate ? 500 : 0, function() {
		$(this).addClass("show");

		if ($(newStep).find("#draggable").length > 0)
			initDragDrop();

		// Update Hash Tag
		if (animate) {
			var path = $(newStep).attr("class");
			
			if (path.indexOf(" ") > 0)
				path = path.substring(0, path.indexOf(" "));
			
			location.hash = path;
		}
	});
	

	var target = ($(newStep).find(".show").length > 0) ? $(newStep).find(".show") : $(newStep);
	// Default Selection
	if (($(target).find("a .text").length == 0) && ($(target).find("input[type='hidden'].text").length > 0)) {
		$("#step_" + step).find("input[type='hidden'][name!='step_BR']").val($(target).find("input[type='hidden'].text").val());
		$(target).find(".next_btn").addClass("current");
	}
	// Preselect when only one option
	else if ($(target).find("a .text").length == 1) {
		$("#step_" + step).find("input[type='hidden'][name!='step_BR']").val($(target).find("a .text").text());
		$(target).find("a").addClass("selected");
		$(target).find(".next_btn").addClass("current");
	}
	if (($("#droppable" ).find("li").length > 0) && step=='7') {
		$(target).find(".next_btn").addClass("current");
	}
	
	/*In case of side wall reset the width*/
	if(step == 6)
	{
		//84 is the width of one sidewall
		var totalOptions = $('.sidewall .sidewall_select').find("li:visible").length;
		var tempWidth = (84*totalOptions) + totalOptions;
		$(".sidewall_select").css('width',tempWidth);
	}
	
	$( "#droppable" ).sortable( "refresh");
}
	
// Zip Code Init
function zipcodeInit() {
	$("#zipcode #submit").click(function() {
		var zipcode = $("#zipcode #zip").val().match(/(\d{5}(-\d{4})?$)|([A-Z]\d[A-Z] \d[A-Z]\d)/gi);
		
		if ((zipcode != null) && ($("#zipcode #zip").val().length == zipcode.toString().length)) {
			$("#zipcode .zipcode_entered span").html($("#zipcode #zip").val());
			
			$("#zipcode .zipcode_main").removeClass("incorrect").hide();
			$("#zipcode .zipcode_entered").show();
			$(".driving_conditions .vehicle_info .zip_callout").text("");
		}
		else
			$("#zipcode .zipcode_main").addClass("incorrect");
	});
	
	$("#zipcode .zipcode_entered a").click(function() {
		$("#zipcode .zipcode_main").show();
		$("#zipcode .zipcode_entered").hide();
	});
	
	$(".zipcode_main a.zip_hint").mouseenter(function() {
		$(this).parent().find(".hint_body").show();
	}).mouseleave(function(){
		$(".hint_body").hide();
	});

}

// Show Modal
var cur_modal;

function showModal(modal) {
    cur_modal = modal;
	
    if (($.browser.msie) && ($.browser.version < 9))
        $(cur_modal).css({ visibility: "visible", display: "block" });
    else
        $(cur_modal).css({ opacity: 0, visibility: "visible", display: "block" }).animate({
            opacity: 1
        });
		
    if (($.browser.msie) && ($.browser.version < 9))
        $("#modal_bg").css('filter', 'alpha(opacity=60)');

    $("#modal_bg").fadeIn();
}

function hideModal(modal) {
	if (modal != null)
    	cur_modal = modal;
		
    if (($.browser.msie) && ($.browser.version < 9))
        $(cur_modal).css({ visibility: "hidden" });
    else
		$(cur_modal).animate({
			opacity: 0
		}, 500, function() {
			$(this).css({ visibility: "hidden" });
		});
	
	$("#modal_bg").fadeOut();
	
	cur_modal = "";
}

function ajexCallToGetResult(selection,step,isBackAction){
	var parseStatus;
	var zipcode = $("#zipcode #zip").val();
	var CompleteUrl = uri_wizard+"?selected="+escape(selection)+"&stepNo="+step+"&isBackAction="+isBackAction+"&zipCode="+zipcode;
		$.ajax({
			type: "GET",
			async: false,
			url: CompleteUrl,
			cache: false,
			timeout: 3000,
			dataType: "xml",
			success:  function(xml) {
			parseStatus =	parse_result_xml(xml,step);
			}
		});
	return parseStatus;
}

function parse_result_xml(result, stepNo)
{
	var noResult = result.getElementsByTagName("No_result")[0].childNodes[0].nodeValue;
	if(noResult=='true')
	{
		$('.no_results').addClass('show');
		return false;
	}
	var stepHeading = result.getElementsByTagName("StepHeading")[0].childNodes[0].nodeValue;
	var stepDesc = result.getElementsByTagName("StepDesc")[0].childNodes[0].nodeValue;
	var stepLength = result.getElementsByTagName("Step").length;
	var nextStepN0 = result.getElementsByTagName("Breadcrumb")[0].childNodes[stepLength-1].getAttribute("moduleNum");
	var nextDispN0 = result.getElementsByTagName("Breadcrumb")[0].childNodes[stepLength-1].getAttribute("displayNum");
	var optionLength = result.getElementsByTagName("option").length;
	var isSelected=false;
	var generalNotes='';
	// Populate the breadCrumb
	for(var index =1;index<=nextDispN0;index++)
	{	
		var dispText = result.getElementsByTagName("Breadcrumb")[0].childNodes[index-1].getAttribute("text");
		var dispValue = result.getElementsByTagName("Breadcrumb")[0].childNodes[index-1].getAttribute("value");
		var moduleNumber = result.getElementsByTagName("Breadcrumb")[0].childNodes[index-1].getAttribute("moduleNum");
		$("#step_" + index).removeClass("current").addClass("show");
		$("#step_" + index + " .progress_tooltip .tooltip_text").text(dispText);

		$("#step_" + moduleNumber).find("input[type='hidden'][name!='step_BR']").val(dispValue);
		document.getElementById("step_BR_"+index).value=moduleNumber;
		
		var selection = dispText;
		if(selection.length >limit)
		if((selection.indexOf(" ",limit-5) < limit) && (selection.indexOf(" ", limit - 5) > 0))
			selection = selection.substring(0, limit)+ "&hellip;";
		else
			selection = selection.substring(0,limit) + "&hellip;";
		
		$("#step_" + index + " a .text").html(selection);
	}
	// Set the step description and heading
	$("#step_" + nextDispN0).addClass("current show");
	var newStep = $("li.tire_selector").eq(nextStepN0 - 1);
	$(newStep).find(".vehicle_info h2 .text").text(stepHeading);
	$(newStep).find(".vehicle_info p").text(stepDesc);
	$(newStep).find(".vehicle_info p span").text(stepDesc);
	
	/*Based upon next step number update the option data*/
	if(nextStepN0 == 2)
	{
		var zipText = "";
		if(result.getElementsByTagName("Zip_Text").length>0 && result.getElementsByTagName("Zip_Text")[0].childNodes.length>0)
			zipText = result.getElementsByTagName("Zip_Text")[0].childNodes[0].nodeValue;
		if(zipText!='')
			$("ul.driving_select").removeAttr('style');

		$(newStep).find('.vehicle_info p').append('<br>');
		$(newStep).find('.vehicle_info p').append($('<span>', {
				'text': zipText,
				'class':'zip_callout'
			}))

		//$(newStep).find(".vehicle_info p span").text(zipText);
		var className = "driving_select options_"+optionLength;
		$(newStep).find("ul").attr('class',className);
		for(var index=0;index<optionLength;index++)
		{
			var name = result.getElementsByTagName("Options")[0].childNodes[index].getAttribute("name")
			var selected = result.getElementsByTagName("Options")[0].childNodes[index].getAttribute("selected")
			var liIndex = optionsMapping[name];
			$(newStep).find(".driving_select li:nth-child("+liIndex+")").attr('style',"display: block;");
			if(selected=='true')
				$(newStep).find(".driving_select li:nth-child("+liIndex+") a").addClass("selected");
		}
	}else if(nextStepN0 == 3)
	{
		$('.footer_note').html('');
		if(result.getElementsByTagName("StepQues").length>0)
		{
			var stepOther = result.getElementsByTagName("StepQues")[0].childNodes[0].nodeValue;
			$('.runflats .vehicle_info p').append('<br>');
			$('.runflats .vehicle_info p').append($('<a>', {
				'href': 'javascript:void(0);',
				'text': stepOther,
				'title': stepOther
			}))
			$(".vehicle_info p a").mouseenter( function() {
				$(this).parents().find(".statement").show();
			}).mouseleave(function() {
				$(".statement").hide();
			});
		}
		$(".runflats .vehicle_info .tire").attr('style','display:block;');
		if(optionLength == 0)
		{
			var defaultVal = result.getElementsByTagName("defaultValue")[0].childNodes[0].nodeValue;

			$(".runflats .vehicle_info .runflat_section").removeClass("choose");
			$(".runflats .vehicle_info .runflat_section").addClass("not_available");
			$(".runflats .vehicle_info .runflat_select").attr('style','display:none;');
			$("#step_3").find("input[type='hidden'][name='Runflat']").val(defaultVal);
			//$("#step_3").find("input[type='hidden'][name='Runflat']").val('Runflat');
			$(".runflats .vehicle_info").find(".next_btn").addClass("current");
			if(result.getElementsByTagName("generalNotes").length>0)
			{
				generalNotes = result.getElementsByTagName("generalNotes")[0].childNodes[0].nodeValue;
				if(generalNotes != ''){
					$('.footer_note').append($('<span>', {
						'class': 'asterisk',
						'text': '*'
					}))
					$('.footer_note').append($('<p>', {
						'text': generalNotes
					}))
				}
			}
		}else{
			$(".runflats .vehicle_info .runflat_select").attr('style','display:block;');
			$(".runflats .vehicle_info .tire").attr('style','display:none;');
			var text = result.getElementsByTagName("Breadcrumb")[0].childNodes[stepLength-1].getAttribute("text");
			var yesSelected = result.getElementsByTagName("Options")[0].childNodes[0].getAttribute("selected");
			if(yesSelected == null || yesSelected == false )
					$(".runflats .vehicle_info .runflat_select .yes").find("a").removeClass("selected");
			var noSelected = result.getElementsByTagName("Options")[0].childNodes[1].getAttribute("selected");
			if(noSelected == null || noSelected == false )
					$(".runflats .vehicle_info .runflat_select .no").find("a").removeClass("selected");
			$('.footer_note').text('');
		}
	}else if(nextStepN0 == 4)
	{
		var temp="";
		for(var index =1;index<=optionLength;index++)
			{
				var optionTextName = result.getElementsByTagName("Options")[0].childNodes[index-1].getAttribute("name");
				var optionTextDesc = result.getElementsByTagName("Options")[0].childNodes[index-1].getAttribute("desc");
				isSelected = result.getElementsByTagName("Options")[0].childNodes[index-1].getAttribute("selected");
				var selectedClass = "";
				if(isSelected=='true')
					selectedClass = "selected";
				var optionTextWOSpace = optionTextName.replace(/ /g, '');
				var liClass = 'select_' + index+' priority_select_btn';
				temp = temp + '<li class="'+liClass+'"><a href="javascript:void(0);" title="" class="'+selectedClass+'"><span class="mark_body float_left"><span class="mark"></span></span><span class="text_body float_left"><span class="text">'+optionTextName+'</span><span class="description">'+optionTextDesc+'</span></span><span class="image"></span></a></li>';
			}
		$('.tire_category .vehicle_info .priority_select ul.scroll-content').html(temp);
		step4Init();

	}else if(nextStepN0 == 5)
	{
			var temp="";
			for(var index =1;index<=optionLength;index++)
			{
					var optionTextName = result.getElementsByTagName("Options")[0].childNodes[index-1].getAttribute("name");
					var optionTextDesc = result.getElementsByTagName("Options")[0].childNodes[index-1].getAttribute("desc");
					var optionTextValue = result.getElementsByTagName("Options")[0].childNodes[index-1].getAttribute("value");
					isSelected = result.getElementsByTagName("Options")[0].childNodes[index-1].getAttribute("selected");
					var selectedClass = "";
					if(isSelected=='true')
						selectedClass = "selected";
					var liClass = 'select_' + index+' priority_select_btn';
					temp = temp + '<li class="'+liClass+'"><a href="javascript:void(0);" title="" class="'+selectedClass+'"><span class="mark_body float_left"><span class="mark"></span></span><span class="text_body float_left"><span class="text">'+optionTextName+'</span><span class="description">'+optionTextDesc+'</span><span class="hide" style="display:none;">'+optionTextValue+'</span></span><span class="image"></span></a></li>';
			}
		$('.vehicle_use .vehicle_info .priority_select ul.scroll-content').html(temp);
		step5Init();
	}else if(nextStepN0 == 6)
	{
			for (var index=0;index<optionLength;index++)
			{
				var optionTextDesc = result.getElementsByTagName("Options")[0].childNodes[index].getAttribute("desc");
				var optionTextValue = result.getElementsByTagName("Options")[0].childNodes[index].getAttribute("value");
				isSelected = result.getElementsByTagName("Options")[0].childNodes[index].getAttribute("selected");
				var buttonEnableClass = optionsMapping[optionTextValue];
				if(isSelected=='true')
				{
					$('.sidewall .vehicle_info .sidewall_select li:nth-child('+buttonEnableClass+') a').addClass('selected') ;
				}

				$('.sidewall .vehicle_info .sidewall_select li:nth-child('+buttonEnableClass+')').attr('style','display:block;');
				$('.sidewall .vehicle_info .sidewall_select li:nth-child('+buttonEnableClass+')').find('span .description').text(optionTextDesc);

				$('.sidewall .vehicle_info .sidewall_select li:nth-child('+buttonEnableClass+')').find('.text').text(optionTextValue);
				$('.sidewall .vehicle_info .sidewall_select li:nth-child('+buttonEnableClass+')').find('.text').attr('style','display:none;');
			}
			$('.sidewall .vehicle_info').removeClass().addClass("vehicle_info options_"+optionLength);

			//84 is the width of one sidewall
			var tempWidth = (84*optionLength) + optionLength;
			$(".sidewall_select").css('width',tempWidth);

	}else if(nextStepN0 == 7)
	{
	
		$('.performance .vehicle_info #draggable').addClass("ui-droppable");
		$('.performance .vehicle_info #droppable').addClass("ui-sortable");
		var tempLeftLi="";
		var tempRightLi="";
		var tempRiteBG="";
		var dragableClass = "ui-state-default ui-draggable";

			for(var index =1;index<=optionLength;index++)
			{
				var optionTextName = result.getElementsByTagName("Options")[0].childNodes[index-1].getAttribute("name");
				var optionTextDesc = result.getElementsByTagName("Options")[0].childNodes[index-1].getAttribute("desc");
				isSelected = result.getElementsByTagName("Options")[0].childNodes[index-1].getAttribute("selected");
				var bgText=priorityDisplay[index];
				if(isSelected=='true')
				{
					dragableClass = "ui-state-default ui-draggable ui-draggable-disabled ui-state-disabled ui-draggable-dropped";
					tempRightLi = tempRightLi + "<li class='ui-state-default ui-draggable ui-draggable-disabled ui-state-disabled ui-state-highlight' aria-disabled='true' style='display: list-item;'><span>"+optionTextName+"</span><span class='mark'></span></li>";
				}
				tempLeftLi = tempLeftLi+"<li class='"+dragableClass+"' aria-disabled='false'><span>"+optionTextName+"</span><span class='mark'></span></li>"
				tempRiteBG = tempRiteBG+"<li class='ui-state-default'>"+bgText+"</li>"
				$('.performance .vehicle_info .question_list li:nth-child('+index+')').find('span .hint_text').text(performanceHelpText[optionTextName]);
			}
			$('.performance .vehicle_info #draggable').html(tempLeftLi);
			$('.performance .vehicle_info #droppable_bg').html(tempRiteBG);
			$('.performance .vehicle_info #droppable').html(tempRightLi);
	}
	isSelected = false;
	for (var index=0;index<optionLength;index++)
	{
		var tempSelected = result.getElementsByTagName("Options")[0].childNodes[index].getAttribute("selected");
		if(tempSelected=='true')
			isSelected = "true";
	}
	if((isSelected == null || isSelected == false) && optionLength>0)
	{
		$("#advisor_content li:nth-child("+nextStepN0+")").find(".next_btn").removeClass("current");
	}
return nextStepN0;
}

// Document Ready
$(document).ready(function() {
	// Init Video Player
	
	$("#modal_bgFancy").click(function()
	{
	      
		$("#winter_tire_modal").hide();
		$("#modal_bgFancy").hide();
		$(".mi-imageMenu").css("z-index","6");
	
		$(".driver").css("visibility","visible");
		$(".engineer").css("visibility","visible");
		$(".designer").css("visibility","visible");
	});
	
	 $(".question_mark a, .question_list a").mouseenter(function(){
	    
		
		 var tooltip = $(this).parent().find(".hint_body");
		 var tooltipText = $(this).parent().find(".hint_body").find(".hint_text").html();
		 

		 
		 sizeofTooltip = ((tooltipText.length < 140) ? (tooltipText.indexOf("img") > 0 ? '300px' : '180px') : ('300px'));
		 $(tooltip).css({ bottom: "-" + (($(tooltip).outerHeight() - $(this).height()) / 2) + "px" }).addClass("show");
	
		 $(tooltip).css('width',sizeofTooltip);
	 }).mouseleave(function() {
	
		$(this).parent().find(".hint_body").removeClass("show");
	 });
		 
	// Init Zip Code
	zipcodeInit();
	
	// Init Steps
	if ($("#home_content").length > 0)
		homePageInit();
	else {
		step1Init();
		step2Init();
		step3Init();
		step4Init();
		step5Init();
		step6Init();
		step7Init();
	
    	// Current Selected
		var step = $("#step_" + ($("#tire_progress li.current.show").index()+1)).find("input[type='hidden'][name='step_BR']").val();
		
		// Shorten the selected value to display.
		  $("#tire_progress li.show").find(".text").each(function(){
			var selection = $(this).text();

			if(selection.length >limit)
			if((selection.indexOf(" ",limit-5) < limit) && (selection.indexOf(" ", limit - 5) > 0))
				selection = selection.substring(0, limit)+ "&hellip;";
			else
				selection = selection.substring(0,limit) + "&hellip;";
				$(this).html(selection);
		})

		// Go to selected step
		var parent = $("li.tire_selector.current.show");

		if ((location.hash != null) && (location.hash.length > 0) && 
			(getQueryString(location.hash.substring(1)) != null) && (getQueryString(location.hash.substring(1)).length > 0))
				parent = $("li." + location.hash.substring(1));
		
		if (parent.length == 0)
			parent = $("li.tire_selector").eq(1);

		gotoStep(step);
		
		// Init Breadcrumbs
		//populateBreadcrumbs();
		
		$("li[id^='step_'] a").click(function() {
			if ($(this).attr("href").indexOf("#") >= 0) {
				var oldStep = $("#advisor_content li.tire_selector.show");
				var oldStepIndex = $("#tire_progress li.show.current").index();
				var newStep = $("li." + $(this).attr("href").substring(1));
				if (oldStepIndex == newStep.index())
				{
					riseBreadCrumbWebAnalyticFunc(oldStepIndex+1,newStep.index()+1);
					return false;
				}	

					var index =	$("#step_" + (newStep.index()+1)).find("input[type='hidden'][name='step_BR']").val();
					var selection = $("#step_" + index).find("input[type='hidden'][name!='step_BR']").val();
					var selectedId = $(this).parents('li.show').index();
					var moduleNum = document.getElementById("step_BR_"+(selectedId+1)).value;
					var nextStepNo = ajexCallToGetResult(selection,moduleNum,true);

					if(nextStepNo=='false')
					{
						return true;
					}

					$(oldStep).fadeOut(500, function() {
						$(this).removeClass("show");
						
						$("li[id^='step_']").each(function(i) {
							if (i > newStep.index())
								$(this).removeClass("current show");
						});
						
						$("#step_" + (newStep.index() + 1)).addClass("current show");
						
						var path = $(newStep).attr("class");
						
						if (path.indexOf(" ") > 0)
							path = path.substring(0, path.indexOf(" "));
						
						location.hash = path;
					});
					
				gotoStep(nextStepNo,false);
				riseBreadCrumbWebAnalyticFunc(oldStepIndex+1,newStep.index()+1);
			}else{
			var oldStepIndex = $("#tire_progress li.show.current").index();
			riseBreadCrumbWebAnalyticFunc(oldStepIndex+1,1);
			}
		});
		
		$("#tire_progress li a").mouseenter(function() {
			$(this).parent().find(".progress_tooltip").show();
		}).mouseleave(function() {
			$(this).parent().find(".progress_tooltip").hide();
		});

		// Bind Next Button
		$(".next_btn").click(function(event, animate) {
			if ($(this).hasClass("current")) {
				var parent = $(this).parents("li.tire_selector");
				var step = $(parent).index() + 1;
			
				if (($(parent).next().length == 0) && ($(this).attr("rel").length > 0)) {
					compileResults($(this).attr("rel"));
					
					return;
				}
			
				var selection = "";
				
				$("#step_" + step).find("input[type='hidden'][name!='step_BR']").each(function() {
					if ($(this).val().length > 0)
						selection += ((selection.length > 0) ? " / " : "") + $(this).val();
				});
				var escapedSelection = escape(selection);
				if(step==7)
				{
					document.fitmentFliter.selected.value=escapedSelection;
					document.fitmentFliter.zipCode.value=$("#zipcode #zip").val();
					document.fitmentFliter.submit();
					riseWebAnalyticPerformanceFunc('Team Michelin - Performance', 0,selection);
					return;
				}
				var tooltip = escapedSelection;
				
				var limit = (step == 1) ? 25 : 16;
				
				var path = $(parent).attr("class");
				
				var nextStepNo = ajexCallToGetResult(escapedSelection,step,false);
				if(nextStepNo=='false')
				{
					return true;
				}
			
				$(parent).fadeOut((animate !== false) ? 500 : 0, function() {

					gotoStep(nextStepNo, (animate !== false));
				});
				
				// Reset Video Player
				$("#video_modal").hide();
				settings.playlist = new Array();
				$("#VideoPlayer").videoplayer("reset");
				var selectionIndex = optionsMapping[selection];
				if(selectionIndex!= undefined)
				{
					riseWebAnalyticFunc(pageNameList[step],(selectionIndex-1),'null')
				}else{
					riseWebAnalyticFunc(pageNameList[step],'0',selection)
				}
			}
		});
	}

		
	
	// Bind Modals	
	/*
	$(".call a, a.call_me").click(function() {
		showModal("#callme_modal");
	});
	*/
	
	$(".call a").fancybox({
		'transitionIn': 'none',
		'transitionOut': 'none',
		'titleShow': false,
		'showCloseButton': false
	});

	$(".read_advice").click(function() {
		var readContent = $(this).parent().find(".read_body");

		readContent.show();
		
		var scrollPane = $(readContent).find(".scroll-pane");
		var scrollContent = scrollPane.find(".scroll-content");
		
		if ( scrollContent.height() <= scrollPane.height() )
			$(scrollPane).find(".scroll-parent").hide();
	});
	$(".read_close").click(function() {
		$(this).parents().find(".read_body").hide();
	});
	$(".vehicle_info p a").mouseenter( function() {
		$(this).parents().find(".statement").show();
	}).mouseleave(function() {
		$(".statement").hide();
	});
	
	$(".magnify").mouseenter(function() {
		$(this).parent().find(".sidewall_link").addClass("hover");	
	}).mouseleave(function(){
		$(".sidewall_link").removeClass("hover");			
	});
	
	// Bind Scroll Bars
	$(".scroll-bar" ).slider({
		orientation: "vertical",
		animate: true,
		value: 100,
		change: function(sender, e) {
					//scrollpane parts
					var scrollPane = $(this).parents(".scroll-pane:first");
					var scrollContent = scrollPane.find(".scroll-content");
					
					if ( scrollContent.height() > scrollPane.height() ) {
						var top = Math.round((100 - e.value) / 100 * ( scrollPane.height() - scrollContent.height() ));
						var step = scrollContent.find("li:first").outerHeight();
						
						top = (Math.round(top / step) * step);
						
						var visible = $(scrollContent).parent().height();
						var total = $(scrollContent).height();
						
						if (top > 0)
							top = 0;
						if (top < visible - total)
							top = visible - total;
						
						var percentage = (100 - Math.round((top / (scrollPane.height() - scrollContent.height())) * 100))
						
						scrollContent.animate({ "margin-top": top }, 150);
						$(this).find("a").animate({ bottom: percentage + "%" }, 150);
					}
				},
		slide:	function(sender, e) {
					//scrollpane parts
					var scrollPane = $(this).parents(".scroll-pane:first");
					var scrollContent = scrollPane.find(".scroll-content");
			
					if ( scrollContent.height() > scrollPane.height() ) {
						var top = Math.round((100 - e.value) / 100 * ( scrollPane.height() - scrollContent.height() ));

						scrollContent.css( "margin-top", top + "px" );
					} else {
						scrollContent.css( "margin-top", 0 );
					}
				}
	});

    // Bind Dropdown Scroll Events
	$(".scroll-pane .scroll-up").click(function() {
		dropdownScroll($(this).parents(".scroll-pane").find(".scroll-content"), 0, 1);
	});
	
	$(".scroll-pane .scroll-down").click(function() {
		dropdownScroll($(this).parents(".scroll-pane").find(".scroll-content"), 0, -1);
	});
	
	$(".scroll-content").mousewheel(function(e, delta) {
		dropdownScroll(this, 0, delta);
	});
	
	//Code to hide quick link elements
	if($("#isTeamMichelin") != 'Enable'){
			$("#utility_widget").hide();
		}
	else{
	$("#utility_widget").show();
	$("#vehicleSubmit").css('width','297px');
	}
			
		
});
function sizeTypeFilter(v) {
		if (v) v=v.toLowerCase().replace(/^[\r\n]+|[\r\n]+$/g, "").substring(0,(v.indexOf("(")-1));
		return v;
	}

function populateDropDowns(temp)
	{
		if (temp == "year")
		{
			onChangeOf = temp;
			toChange = "make";
			makes.splice(0, makes.length);
			models.splice(0, models.length);
			options.splice(0, options.length);
			sizes.splice(0, sizes.length);
			$("#size").val('');
			vehicleData.splice(4, vehicleData.length);
			$('li.option-5').hide();
			$('li.tooltip-option-5').hide();
			var yearValue = document.getElementById('year').value;
			if(yearValue != '-1'){
				ajaxParam=temp+"&yearValue="+yearValue;
					ajaxWidgetCall(ajaxParam,toChange);
			}
		}
		if(temp == "make")
		{
			var yearValue = document.getElementById('year').value;
			var makeValue = document.getElementById('make').value;	
			
			onChangeOf = temp;
			toChange = "model";
			models.splice(0, models.length);
			options.splice(0, options.length);
			sizes.splice(0, sizes.length);
			$("#size").val('');
			vehicleData.splice(4, vehicleData.length);
			$('li.option-5').hide();
			$('li.tooltip-option-5').hide();
			if(makeValue != '-1'){
				ajaxParam=temp+"&yearValue="+yearValue+"&makeValue="+escape(makeValue);
				ajaxWidgetCall(ajaxParam,toChange);
			}
		}
		if(temp == "model")
		{
			var yearValue = document.getElementById('year').value;
			var makeValue = document.getElementById('make').value;
			var modelValue = document.getElementById('model').value;
			onChangeOf = temp;
			toChange = "options";
			options.splice(0, options.length);
			sizes.splice(0, sizes.length);
			$("#size").val('');
			vehicleData.splice(4, vehicleData.length);
			$('li.option-5').hide();
			$('li.tooltip-option-5').hide();
			if(modelValue != '-1'){
				ajaxParam=temp+"&yearValue="+yearValue+"&makeValue="+escape(makeValue)+"&modelValue="+escape(modelValue);
				ajaxWidgetCall(ajaxParam,toChange);
			}
		}
		if(temp == "options")
		{
			var yearValue = document.getElementById('year').value;
			var makeValue = document.getElementById('make').value;
			var modelValue = document.getElementById('model').value;
			var optionValue = document.getElementById('options').value;
			sizes.splice(0, sizes.length);
			$("#size").val('');
			vehicleData.splice(4, vehicleData.length);
			$('li.option-5').hide();
			$('li.tooltip-option-5').hide();
			onChangeOf = temp;
			toChange = "tireSize";
			if(optionValue != '-1'){
				
				ajaxParam=temp+"&yearValue="+yearValue+"&makeValue="+escape(makeValue)+"&modelValue="+escape(modelValue)+"&optionValue="+escape(optionValue);
				ajaxWidgetCall(ajaxParam,toChange);
			}
		}
	
		if(temp == "size")
		{
			var sizeTypeValue= document.getElementById('sizeType').value;
			if(sizeTypeValue != '-1'){
				widths.splice(0, widths.length);
				aspects.splice(0, aspects.length);
				rimSizes.splice(0, rimSizes.length);
				onChangeOf = temp;
				toChange = "width";
				ajaxParam=temp+"&sizeTypeValue="+sizeTypeFilter(sizeTypeValue);
				ajaxWidgetCall(ajaxParam,toChange);
			}
		}
		if(temp == "width")
		{
			var sizeTypeValue= document.getElementById('sizeType').value;
			var widthValue= document.getElementById('width').value;	
			
			if(widthValue != '-1'){
				aspects.splice(0, aspects.length);
				rimSizes.splice(0, rimSizes.length);
				onChangeOf = temp;
				tochange = "aspectratio";
				ajaxParam=temp+"&sizeTypeValue="+sizeTypeFilter(sizeTypeValue)+"&widthValue="+widthValue;
				ajaxWidgetCall(ajaxParam,'aspectratio');
			}
		}
		if(temp == "aspectratio")
		{
			var sizeTypeValue= document.getElementById('sizeType').value;
			var widthValue= document.getElementById('width').value;
			var aspectValue = document.getElementById('aspectratio').value;	
			
			if(aspectValue != '-1'){
				rimSizes.splice(0, rimSizes.length);
				onChangeOf = temp;
				tochange = 'diameter';
				ajaxParam=temp+"&sizeTypeValue="+sizeTypeFilter(sizeTypeValue)+"&widthValue="+widthValue+"&aspectValue="+aspectValue;
				ajaxWidgetCall(ajaxParam,'diameter');
			}
		}
	}
function ajaxWidgetCall(ajaxParam,toChange)
	{ 	
		$.ajax({
			type: "GET",
			async: false,
			cache: false,
			timeout: 3000,
			url: uri_widget+"?type="+ajaxParam+"&ajaxCall=true",
			dataType: "xml",
			success: function(xml){
						parsewidgetxml(xml,toChange);
					}                 	  
		});
	}
	
 function parsewidgetxml(result,toChange)
	{	
		if(toChange == 'winterNonWinterCountYMMO')
		{
			var singleTireString = 'Tire';
			var multipleTireString = 'Tires';
			var differentWinterTires = result.getElementsByTagName("winterCount");
			if(differentWinterTires.length > 0){
				var winterCount = differentWinterTires[0].getAttribute("winter_count");                                  
				var nonWinterCount = differentWinterTires[0].getAttribute("Non_winter_count");
				if(nonWinterCount < 1){
					submitCTSPage('vehicle','no');
				} else {
					if(winterCount == 1)
						$("#winter_Count").text(winterCount +" "+singleTireString);
					else
						$("#winter_Count").text(winterCount +" "+multipleTireString);
					if(nonWinterCount == 1)	
						$("#nonWinter_Count").text(nonWinterCount +" "+singleTireString);
					else
						$("#nonWinter_Count").text(nonWinterCount +" "+multipleTireString);
					
					$("#findTireSnow").attr('onclick', "submitCTSPage('vehicle','yes');");
					$('#findTireSnow').live('click', function() {
						submitCTSPage("vehicle","yes");
						findAllClicked = true;
						// Live handler called.
					});
					
					$("#modal_bgFancy").show();
					$(".mi-imageMenu").css("z-index","5");
					$("#winter_tire_modal").show();
					$(".driver").css("visibility","hidden");
					$(".engineer").css("visibility","hidden");
					$(".designer").css("visibility","hidden");
						
				}
			} else {
				submitCTSPage('vehicle','no');
			}
		} else if(toChange == 'winterNonWinterCountSize')
		{
			var singleTireString = 'Tire';
			var multipleTireString = 'Tires';
			var differentWinterTires = result.getElementsByTagName("winterCount");
			if(differentWinterTires.length > 0){
				var winterCount = differentWinterTires[0].getAttribute("winter_count");                                  
				var nonWinterCount = differentWinterTires[0].getAttribute("Non_winter_count");
				if(nonWinterCount < 1){
					submitCTSPage('size','no');
				} else {
					if(winterCount == 1)
						$("#winter_Count").text(winterCount +" "+singleTireString);
					else
						$("#winter_Count").text(winterCount +" "+multipleTireString);
					if(nonWinterCount == 1 )	
						$("#nonWinter_Count").text(nonWinterCount +" "+singleTireString);
					else
						$("#nonWinter_Count").text(nonWinterCount +" "+multipleTireString);
					
					$("#findTireSnow").attr('onclick', "submitCTSPage('size','yes');");
					$('#findTireSnow').live('click', function() {
						submitCTSPage("size","yes");
						findAllClicked = true;
						// Live handler called.
					});
					
					$("#modal_bgFancy").show();
					$(".mi-imageMenu").css("z-index","5");
					
					$("#winter_tire_modal").show();
				}
			} else {
				submitCTSPage('size','no');
			}
		} else {
			var dnl = result.getElementsByTagName(toChange);
			for (var i=0; i < dnl.length; i++) 
			{ 
				var val;
				if(toChange == 'tireSize')
					val = dnl[i].getAttribute(toChange+"_name");
				else
					val = dnl[i].getAttribute(toChange+"_value");
				if(toChange == 'make')
					makes.push(val.toString());
					
				if(toChange == 'model')
					models.push(val.toString());
					
				if(toChange == 'options')
					options.push(val.toString());
				
				if(toChange == 'tireSize')
					sizes.push(val.toString());
					
				if(toChange == 'width')
					widths.push(val.toString());
					
				if(toChange == 'aspectratio')
					aspects.push(val.toString());
					
				if(toChange == 'diameter')
				rimSizes.push(val.toString());
			}
			if(toChange == 'tireSize' && sizes.length > 0){
				homePageContentInit(homePageGuideSearchUpdate,'size'); 
				$('li.option-5').show();
				$('li.tooltip-option-5').show();
			} else {
				//homePageContentInit(homePageGuideSearchUpdate,'xyz'); 
				$("#size").val('');
			}
		}
		
	}

function submitCTSPage(methodName, winterOrNot)
	{
		var searchTypeExisting = document.getElementById('searchType');
			if(searchTypeExisting)
			document.removeChild(searchTypeExisting);
		var searchType=document.createElement("input");
		searchType.setAttribute("type", "hidden");
		searchType.setAttribute("id", "searchType");
		searchType.setAttribute("name", "searchType");
		searchType.setAttribute("value", methodName);
		if(!Array.indexOf){
		  Array.prototype.indexOf = function(obj){
		   for(var i=0; i<this.length; i++){
			if(this[i]==obj){
			 return i;
			}
		   }
		   return -1;
		  }
		}
		if(methodName == 'vehicle')
		{
			var winterTires=document.createElement("input");
			winterTires.setAttribute("type", "hidden");
			winterTires.setAttribute("id", "winterNonWinter");
			winterTires.setAttribute("name", "winterNonWinter");
	
			var winterDiv = document.getElementById('winterNonWinter');
			if(winterDiv != null)
			document.forms["vehicle"].removeChild(winterDiv);
			
			if(winterOrNot == 'yes'){
				document.forms["vehicle"].appendChild(winterTires);
				if($('input:radio[name=winter]:checked').val() == 'Winter Tires')
					document.getElementById('winterNonWinter').value = "true";
				else
					document.getElementById('winterNonWinter').value = "false";
			}
			// Set data in cookie.
			var yearCookie	= document.getElementById('year').value;
			var makeCookie	= document.getElementById('make').value;
			var modelCookie	= document.getElementById('model').value;
			var optionsCookie	= document.getElementById('options').value;
			var tireSizeCookie = document.getElementById('size').value
			$.cookie('type', 'vehicle', { expires: 180 , path: '/' });
			$.cookie('year', yearCookie ,{ expires: 180, path: '/' });
			$.cookie('make', makeCookie ,{ expires: 180 , path: '/'});
			$.cookie('model', modelCookie ,{ expires: 180 , path: '/'});
			$.cookie('options', optionsCookie ,{ expires: 180 , path: '/'});
			if(tireSizeCookie != "" && tireSizeCookie != undefined && tireSizeCookie != null)
			{
				var index = sizes.indexOf(tireSizeCookie);
				tireSizeCookie = tireSizeCookie+index
				$.cookie('tireSize', tireSizeCookie ,{ expires: 180 , path: '/'});
				document.getElementById('size').value = tireSizeCookie;
				
			}
			$.cookie('size', null,{path: '/' });
			$.cookie('width', null,{path: '/' });
			$.cookie('aspectratio', null),{path: '/' };
			$.cookie('diameter', null,{path: '/' });
			$.cookie('name', null,{path: '/' });
			$.cookie('category', null,{path: '/' });
			
			document.forms["vehicle"].appendChild(searchType);
			document.forms["vehicle"].submit();
		}
		if(methodName == 'guided')
		{
			// Set data in cookie.
			var yearCookie	= document.getElementById('year').value;
			var makeCookie	= document.getElementById('make').value;
			var modelCookie	= document.getElementById('model').value;
			var optionsCookie	= document.getElementById('options').value;
			var tireSizeCookie = document.getElementById('size').value
			$.cookie('type', 'vehicle', { expires: 180 , path: '/' });
			$.cookie('year', yearCookie ,{ expires: 180, path: '/' });
			$.cookie('make', makeCookie ,{ expires: 180 , path: '/'});
			$.cookie('model', modelCookie ,{ expires: 180 , path: '/'});
			$.cookie('options', optionsCookie ,{ expires: 180 , path: '/'});
			if(tireSizeCookie != "" && tireSizeCookie != undefined && tireSizeCookie != null)
			{
				var index = sizes.indexOf(tireSizeCookie);
				tireSizeCookie = tireSizeCookie+index
				$.cookie('tireSize', tireSizeCookie ,{ expires: 180 , path: '/'});
				document.getElementById('size').value = tireSizeCookie;
				
			}
			$.cookie('size', null,{path: '/' });
			$.cookie('width', null,{path: '/' });
			$.cookie('aspectratio', null),{path: '/' };
			$.cookie('diameter', null,{path: '/' });
			$.cookie('name', null,{path: '/' });
			$.cookie('category', null,{path: '/' });
			document.forms["vehicle"].appendChild(searchType);
			document.forms["vehicle"].submit();
		}
		if(methodName == 'size')
		{
			var winterTires=document.createElement("input");
			winterTires.setAttribute("type", "hidden");
			winterTires.setAttribute("id", "winterNonWinterSize");
			winterTires.setAttribute("name", "winterNonWinterSize");
	
			var winterDiv = document.getElementById('winterNonWinterSize');
			if(winterDiv != null)
			document.forms["tiresize"].removeChild(winterDiv);
			
			if(winterOrNot == 'yes'){
				document.forms["tiresize"].appendChild(winterTires);
				if($('input:radio[name=winter]:checked').val() == 'Winter Tires')
					document.getElementById('winterNonWinterSize').value = "true";
				else
					document.getElementById('winterNonWinterSize').value = "false";
			}
			// Set data in cookie.
			var sizeCookie = document.getElementById('sizeType').value;
			var widthCookie	= document.getElementById('width').value;
			var aspectratioCookie = document.getElementById('aspectratio').value;
			var diameterCookie = document.getElementById('diameter').value;
			$.cookie('type', 'size', { expires: 180 , path: '/' });
			$.cookie('year', null,{path: '/' });
			$.cookie('make', null,{path: '/' });
			$.cookie('model', null,{path: '/' });
			$.cookie('options', null,{path: '/' });
			$.cookie('tireSize', null,{path: '/' });
			$.cookie('size', sizeTypeFilter(sizeCookie) ,{ expires: 180, path: '/' });
			$.cookie('width', widthCookie ,{ expires: 180, path: '/' });
			$.cookie('aspectratio', aspectratioCookie ,{ expires: 180, path: '/' });
			$.cookie('diameter', diameterCookie ,{ expires: 180, path: '/' });
			$.cookie('name', null,{path: '/' });
			$.cookie('category', null,{path: '/' });
			
			document.forms["tiresize"].appendChild(searchType);
			document.forms["tiresize"].submit();
		}
		if(methodName == 'category')
		{
			// Set data in cookie.
			var categoryCookie = $('input[name="Select Tire Category"]').val();
			var categoryCookie1 = categoryCookie.replace('\u00E9', 'e').toLowerCase().replace(/\//g,'-').replace(/[^a-zA-Z0-9\s-]/g,'').replace(/\s/g,'-');
			
			$.cookie('type', 'category', { expires: 180 , path: '/' });
			$.cookie('year', null,{path: '/' });
			$.cookie('make', null,{path: '/' });
			$.cookie('model', null,{path: '/' });
			$.cookie('options', null,{path: '/' });
			$.cookie('tireSize', null,{path: '/' });
			$.cookie('size', null,{path: '/' });
			$.cookie('width', null,{path: '/' });
			$.cookie('aspectratio', null),{path: '/' };
			$.cookie('diameter', null,{path: '/' });
			$.cookie('name', null,{path: '/' });
			$.cookie('category', categoryCookie1 ,{ expires: 180, path: '/' });
			
			document.forms["tirecategory"].appendChild(searchType);
			document.forms["tirecategory"].submit();
		}
		if(methodName == 'name')
		{
		
			// Set data in cookie.
			var nameCookie = $('input[name="Select Tire Name"]').val();
			var nameCookie1 = nameCookie.replace('\u00E9', 'e').toLowerCase().replace(/\//g,'-').replace(/[^a-zA-Z0-9\s-]/g,'').replace(/\s/g,'-');
			$.cookie('type', 'name', { expires: 180 , path: '/' });
			$.cookie('year', null,{path: '/' });
			$.cookie('make', null,{path: '/' });
			$.cookie('model', null,{path: '/' });
			$.cookie('options', null,{path: '/' });
			$.cookie('tireSize', null,{path: '/' });
			$.cookie('size', null,{path: '/' });
			$.cookie('width', null,{path: '/' });
			$.cookie('aspectratio', null),{path: '/' };
			$.cookie('diameter', null,{path: '/' });
			$.cookie('name', nameCookie1 ,{ expires: 180, path: '/' });
			$.cookie('category', null,{path: '/' });
			
			document.forms["tirename"].appendChild(searchType);
			document.forms["tirename"].submit();
		}
	}

function checkForWinter(methodName)
	{  
	   
		if(methodName == 'vehicle')
		{
		 	var yearValue = document.getElementById('year').value;
			var makeValue = document.getElementById('make').value;
			var modelValue = document.getElementById('model').value;
			var optionValue = document.getElementById('options').value;
			var tireSize = document.getElementById('size').value;		
			
			makeValue = escape(makeValue);
			modelValue = escape(modelValue);
			optionValue = escape(optionValue);			
				if(!Array.indexOf){
  Array.prototype.indexOf = function(obj){
   for(var i=0; i<this.length; i++){
    if(this[i]==obj){
     return i;
    }
   }
   return -1;
  }
}
			var index = sizes.indexOf(tireSize);
			tireSize = tireSize+index			
			
			tochange = 'winterNonWinterCountYMMO';
			var winterCount="winterCount&yearValue="+yearValue+"&makeValue="+makeValue+"&modelValue="+modelValue+"&optionValue="+optionValue+"&tireSize="+tireSize;
			ajaxWidgetCall(winterCount,tochange);
		} else if(methodName == 'size'){
			var sizeTypeValue= document.getElementById('sizeType').value;
			var widthValue= document.getElementById('width').value;
			var aspectValue = document.getElementById('aspectratio').value;	
			var diameterValue = document.getElementById('diameter').value;		
			
			sizeValue = escape(sizeTypeFilter(sizeTypeValue));
			widthValue = escape(widthValue);
			aspectValue = escape(aspectValue);
			diameterValue = escape(diameterValue);
			
			tochange = 'winterNonWinterCountSize';
			var winterCount="winterCountSize&sizeTypeValue="+sizeValue+"&widthValue="+widthValue+"&aspectValue="+aspectValue+"&rimValue="+diameterValue;
			ajaxWidgetCall(winterCount,tochange);
		}
	}

function riseMediaTrackingJS(mediaSrcID, mediaTypeID, mediaCatID, isOnTMPage)
{
		if(isOnTMPage == "NOBG"){
			var axel = Math.random() + "";
			var a = axel * 10000000000000;
			$("#home_content").append('<iframe src="http://fls.doubleclick.net/activityi;src='+mediaSrcID+';type='+mediaTypeID+';cat='+mediaCatID+';ord=' + a + '?" width="1" height="1" frameborder="0" style="display:none"></iframe>'); 
}	
}
